Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django accessing a session outside of a view
I need to access a session outside of my view in a custom template filter, however don't know how to access the specific item in the list of current sessions, my Views.py looks like this: def handle_rebase(request): total_increase = 1 request.session["global_rebase"] = total_increase return HttpResponse(total_increase) The Django docs show the following snippet: >>> from django.contrib.sessions.models import Session >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead') >>> s.expire_date However how do I determine the 'pk' of request.session["global_rebase"] ? -
mocking attribute of class that is used in tested class
I'm trying to write unit tests for my django app but failing to correctly use mock.patch my code : apps\MyApp\DataAccessLayer\CctDAO.py : from ..models import CCT from ..serializers import CctSerializer """ get a list of all CCTs @return a list of all the CCTs """ def getAll() -> list[dict]: entities = CCT.objects.all() serializer = CctSerializer(entities, many=True) return serializer.data apps\Myapp\serializers.py : from rest_framework_mongoengine.serializers import DocumentSerializer from .models import CCT """ serializer to encode and decode Yadbar CCT to JSON """ class CctSerializer(DocumentSerializer): class Meta: model = CCT exclude = ('id', ) #using custom id field instead of the default my test case : from unittest import TestCase, mock from .DataAccessLayer import CctDAO class Test_CCT_DAO(TestCase) : # @mock.patch('apps.MyApp.DataAccessLayer.CctDAO.CCT.objects.all', return_value=['mocked-data1']) @mock.patch.object(CctDAO.CctSerializer, 'data', new_callable=mock.PropertyMock, return_value = ['mocked-data1']) def test_getall_empty(self, mock1=None, mock2=None): print(CctDAO.getAll()) self.assertEqual(['mocked-data2'], CctDAO.getAll()) in this test case CctDAO.getAll() returns [], abd not my mocked data I also tried @mock.patch.object(CctDAO, 'CctSerializer.data', new_callable=mock.PropertyMock, return_value = ['mocked-data1']) but this results in an error that the CctDAO module does not have the attribute 'CctSerializer.data' I also tried @mock.patch('apps.MyApp.DataAccessLayer.CctDAO.CctSerializer.data', new_callable=mock.PropertyMock, return_value=['mocked-data1']) which returns [] as well, and not the mocked data how am I supose to patch CCT.objects.all() and serializer.data correctly? thanks -
Any one used "django-sqlcipher" for encrypting SQLITE ? I want to encrypt SQLITE database in Django
I am working on Windows OS. I want to encrypt my SQLite3 database in Django. I have installed "django-sqlcipher" and add "sqlcipher" in my InstalledAPPS. After that, I added "sqlcipher.backend" in my database Engine. when I run my project I get this error django.core.exceptions.ImproperlyConfigured: 'sqlcipher.backend' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in back ends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' If anyone of you faced this issue already please do let me know. -
Django : retrieve data from models
I have a serious problem, I need to retrieve a query set from an unrelated model my model: # problem/models.py User = get_user_model() class Problem(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000) writer = models.ForeignKey(User,models.CASCADE) score = models.PositiveIntegerField(default=100) # my perfer is PositiveSmallIntegerField class Submission(models.Model): submitted_time = models.DateTimeField(auto_now_add=True) participant = models.ForeignKey(User,related_name="submissions",on_delete=models.CASCADE) problem = models.ForeignKey(Problem,related_name="submissions",on_delete=models.CASCADE) code = models.URLField(max_length=200) score = models.PositiveIntegerField(default=0) # contest/models.py class Contest(models.Model): name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time = models.DateTimeField() is_monetary = models.BooleanField(default=False) price = models.PositiveIntegerField(default=0) problems = models.ManyToManyField(Problem) authors = models.ManyToManyField(User, related_name='authors') participants = models.ManyToManyField(User, related_name='participants') I trying to retrieve a query set of Submission like this : <QuerySet [<Submission: Submission object (12)>, <Submission: Submission object (6)>, <Submission: Submission object (16)>, <Submission: Submission object (5)>, <Submission: Submission object (11)>, <Submission: Submission object (15)>, <Submission: Submission object (14)>, <Submission: Submission object (4)>, <Submission: Submission object (10)>, <Submission: Submission object (9)>, <Submission: Submission object (3)>, <Submission: Submission object (8)>, <Submission: Submission object (2)>, <Submission: Submission object (13)>, <Submission: Submission object (1)>, <Submission: Submission object (7)>]> with the id of the Contest model , but I don't know how it is possible -
Many To Many display field Django
I have 4 models Account (a Custom User model) TeacherProfile (that have a foreign key to the Account) Section (that have a foreign key to the TeacherProfile) Subject (Many to Many to Student and Teacher) Now I want my Django-Admin to show whenever I'm going to Subject, this instance <Subject 1> under <Teacher 1> <Subject 1> under <Teacher 7> How could I do this? -
i see an error during making a virtual Environment
im making a ew project and start like this: (enviro) PS C:\Users\MadYar\Desktop\code.py\learning_log> django-admin.py startproject learning_log . and Error: The term 'django-admin.py' is not recognized as the name of a cmdlet, function, script file, or operable pr ogram. Check the spelling of the name, or if a path was included, verify that the path is correct and try a gain. At line:1 char:16 django-admin.py <<<< startproject learning_log . CategoryInfo : ObjectNotFound: (django-admin.py:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException -
Getting the error socket.gaierror: [Errno 11003] getaddrinfo failed when using Django Channels
I am setting up Websockets using Django Channels, sending a test message when the relevant API end point is triggered. However when I try to use Postman to test my websocket connection, I successfully connect, receive the JSON I am sending and immediately get disconnected. This is the full traceback: redis.exceptions.ConnectionError: Error 10061 connecting to localhost:49155. No connection could be made because the target machine actively refused it. HTTP GET /media/profile/2022/06/10/photo-1615672968435-95ade28e0b38.jpg 500 [4.47, 127.0.0.1:51105] HTTP GET /users/1/ 500 [4.46, 127.0.0.1:51106] WebSocket HANDSHAKING /stories/notification_testing/ [127.0.0.1:50570] {'type': 'websocket', 'path': '/stories/notification_testing/', 'raw_path': b'/stories/notification_testing/', 'headers': [(b'sec-websocket-version', b'13' ), (b'sec-websocket-key', b'TcKbMvNYlHQtJdO5efSXDQ=='), (b'connection', b'Upgrade'), (b'upgrade', b'websocket'), (b'sec-websocket-extensions', b'permessage -deflate; client_max_window_bits'), (b'host', b'127.0.0.1:8000')], 'query_string': b'', 'client': ['127.0.0.1', 50570], 'server': ['127.0.0.1', 8000], 'sub protocols': [], 'asgi': {'version': '3.0'}, 'cookies': {}, 'session': <django.utils.functional.LazyObject object at 0x00000207DC59A5E0>, 'user': <channels.auth.UserLazyObject object at 0x00000207D8D5A820>, 'path_remaining': '', 'url_route': {'args': (), 'kwargs': {}}} WebSocket CONNECT /stories/notification_testing/ [127.0.0.1:50570] Exception inside application: [Errno 11003] getaddrinfo failed Traceback (most recent call last): ... File "C:\Users\15512\Desktop\django-project\peerplatform\signup\consumers.py", line 31, in websocket_connect await self.channel_layer.group_add(self.room_group_name, self.channel_name) ... for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11003] getaddrinfo failed WebSocket DISCONNECT /stories/notification_testing/ [127.0.0.1:50570] I am running Redis through a Django image, I am already using a Redis cache for … -
Django and Pyerbase ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory
I am trying to use pyerbase in a django project and I keep getting this error. I am on my 2nd or 3rd hour of research on how to get this to work and now I am running into this issues. enter image description here enter image description here I have looked at all of the other stack overflow post about this issue. The long char path limit was already a 1 in my registry and I have a doubt that this was my problem in the first place. I tried a few other things like even trying to pip install the package directly into the folder that it is looking for. enter image description here I am just looking for another answer because the stuff that has been suggested is not working. An I noticed that the other questions are about scikit and tensorflow but none about pyerbase. I also check the site-packages for my venv and urllib3 is not in there. -
Is there a way to disallow login during cool off time for django-axes
In most sites when locked out, the user is not allowed to retry and enter the site unless the cool off period expires or is unlocked by an admin. However the default behavior of django-axes allows the user to log in successfully during the cool off time. Is there anyway to disable this? -
How can I prevent my Django Model from creating a "deferred attribute" for one of my model columns?
Below is my model for "RunCounts" class RunCounts(models.Model): AccountUsername = models.TextField(blank = True) RunDate = models.DateTimeField(null=True) Report = models.TextField(blank = False) When I later try to reference this in my views.py I cannot filter on the RunDate like I can all the other values in the model. Below is an example of me attempting to filter on it. test = RunCounts.objects.filter(RunCounts.RunDate >= '2022-07-13') returns the error: '>=' not supported between instances of 'DeferredAttribute' and 'str' how can I either prevent django from making my RunDate column a 'DeferredAttribute' or be able to still use it in the filter? -
How to make the text of posts in Django Admin limited by characters?
For example I want the column with the text here to be limited to 15 characters so as not to clutter up the space and make it easier to navigate through the posts. models.py class Post(models.Model): text = models.TextField(verbose_name='Содержание поста') pub_date = models.DateTimeField( verbose_name='Дата публикации', auto_now_add=True ) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts', verbose_name='Автор', ) group = models.ForeignKey( 'Group', blank=True, null=True, on_delete=models.SET_NULL, related_name='posts', verbose_name='Группа', ) class Meta: ordering = ('-pub_date',) def __str__(self): return self.text -
Defensive programming for delete function in views Django
I am fairly new to Django, and I got some feedback for my project (recipe app) that I am currently working on from my mentor about defensive programming. I have created a delete "function" in my app views in Django, and he told me to remake the function so no one else than the author of the recipe could ever delete the selected recipe. I have included authentication for this in my HTML but he told me to do the same for my delete view. Does anyone have a good explanation for how I could achieve this in a simple way? I have never before asked a question here so give me feedback if I have provided the right information for a question like this. Here is my delete view today: def delete_recipe(request, slug): """ View for delete recipe """ recipe = Recipe.objects.get(slug=slug) recipe.delete() return redirect('home') -
django_auth_ldap format requires a mapping
i try to use LDAP for my Django Application. Current is the Problem that the import of the Userbase is coorect. But its only possible that the user can login if the user is an admin. Its not possible to login with the staff flag. What should I do ? AUTH_LDAP_USER_SEARCH = LDAPSearch( "OU=Crypted...... "sAMAccountName=%(user)s" ) Set up the basic group parameters. AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "OU=Cryped.....", ldap.SCOPE_SUBTREE, "sAMAccountName=%(user)s", "(objectClass=groupOfNames)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") # Simple group restrictions AUTH_LDAP_REQUIRE_GROUP = "DefinitionCrypted" # Populate the Django user from the LDAP directory. AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "DefinitionCrypted", "is_staff": "DefinitionCrypted", } # This is the default, but I like to be explicit. AUTH_LDAP_ALWAYS_UPDATE_USER = True # Use LDAP group membership to calculate group permissions. AUTH_LDAP_FIND_GROUP_PERMS = True # Cache distinguished names and group memberships for an hour to minimize # LDAP traffic. AUTH_LDAP_CACHE_TIMEOUT = 3600 # Keep ModelBackend around for per-user permissions and maybe a local # superuser. AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "django_auth_ldap.backend.LDAPBackend", ) -
can't access to members of ManyToManyField
I want to get the products which are connect to my form like:['shirt' , 'hat'] but this gives me the bound method Manager insted of Queryset in models.py from django.db import models from eshop_product.models import Product class Form(models.Model): user_name = models.CharField(max_length=600, null=True, blank=True) first_name = models.CharField(max_length=600, null=True, blank=True) products = models.ManyToManyField(Product, blank=True) in views.py def checkOut(request): user = request.user products = Form.objects.filter(user_name=user.username)[0].products.all for product in products: print(product.title) This is the returned error: 'ManyRelatedManager' object is not iterable -
'DiscordUser' object has no attribute 'is_active' Django
I try to go http://localhost:8000/admin/ but I have this error, I just make DiscordUser for oauth2 in site, not admin AttributeError at /admin/ 'DiscordUser' object has no attribute 'is_active' with my model code: class DiscordUser(models.Model): objects = DiscordUserOAuthManager() id = models.BigIntegerField(primary_key=True) discord_tag = models.CharField(max_length=100) avatar = models.CharField(max_length=100) public_flags = models.IntegerField() flags = models.IntegerField() locale = models.CharField(max_length=100) mfa_enabled = models.BooleanField() last_login = models.DateTimeField(null = True) def is_authenticated(self,request): return True -
Django This field is required
So here is a problem im trying to get access to my cart but in the moment when i call is_valid func it says @ ="errorlist">quantity<ul class="errorlist" This field is required.@ i am a newbie in Django still dont have any idea what im doing wrong. If anyone could give me some advise or solution.. cart.forms.py 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) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) cart.views.py from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @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'], update_quantity=cd['update']) print(form.errors) return redirect('cart:cart_detail') 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') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) cart.cart.py from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified … -
Insert Multiple Json Data Separated with Comma Django
Json Data: { "videos":[ { "video":{ "duration":"12:15", "views":340827, "video_id":"39409821", "rating":"71.9337", "ratings":905, "title":"EXAMPLE TITLE", "url":"https:\/\/www.example.com\/39409821", "embed_url":"https:\/\/embed.example.com\/?id=39409821", "default_thumb":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=e0YH8f)(mh=GF_hOaEdP3ot9Hzb)7.jpg", "thumb":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=e0YH8f)(mh=GF_hOaEdP3ot9Hzb)7.jpg", "publish_date":"2021-04-12 01:10:17", "thumbs":[ { "size":"big", "width":432, "height":324, "src":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)1.jpg" }, { "size":"big", "width":432, "height":324, "src":"https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)2.jpg" } ], "tags":[ { "tag_name":"A" }, { "tag_name":"B " }, { "tag_name":"C" } ] } } ] } Function for insert videos to database def apivideo(request): apivideos = {} categoris = ["a","b","c","d","e"] if request.method == 'POST': url = "https://api.example.com/?data=example.Videos.searchVideos&output=json&search="+random.choice(categoris)+"&tags[]="+random.choice(categoris)+"&thumbsize=big&page=1" response = requests.get(url) data = response.json() Videos = data['videos'] for i in Videos: video_data = Video( video_title = i['video']['title'], video_description = i['video']['title'], video_slug = slugify(i['video']['title']), video_url = "<iframe src=\""+i['video']['embed_url']+"\" frameborder=\"0\" width=\"1200\" height=\"720\" scrolling=\"no\" allowfullscreen></iframe>\"", video_category = i['video']['title'], video_img = i['video']['thumbs'][0]['src'], ) video_data.save() I want to add all tags and thumbs to the database as comma separated text. I want to loop through the view html file and show all thumbs. (If there is a more effective way to do this, please share with me). The API provides 16 thumbs for each video. I will use these images for the video preview so I need all the images for each video. I already tried: i['video']['thumbs']['src'] i['video']['thumbs'][indexnumber]['src'] What i want : thumbs = ["https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)1.jpg","https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)2.jpg"] Or thumbs = "https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)2.jpg,https:\/\/di-ph.example.com\/videos\/202104\/12\/386477821\/original\/(m=eWgr9f)(mh=2cyTVZ1O4oPX4IPi)3.jpg" -
List view by query foreign key django
I an application which you can create project and each project is going to have some reports, In my main page it shows the users projects which includes ( Reference, Project Type, Project Name and Date), and you can create report and in report there is a foreign key which you can choose to point to specific project, I want when user click on reference of project, application shows the list of reports that is related to that project This is my Models.py -
Django REST Framework: Changing keys during deserialization
Im writing a little app in Django using the djangorestframework. The goal is pretty simple: I want to be able to get a request per http POST method with a json-object attached to it. At the end I want to return the same json-object but with different key values. To be precise I want to translate the key values from german to english. So this is what I would get: { "vorname": "John", "nachname": "Doe" } And this is what I want to return: { "firstname": "John", "lastname": "Doe" } Im trying to do this using a serializer and it kinda works already, just not in the way I would like it to work. This is the model im using: class Name(models.Model): firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) And this is the serializer: class NameSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Name fields = ['firstname', 'lastname'] And of course there is also a view: @api_view(['POST']) @parser_classes([JSONParser]) def convert(request): request.data['firstname'] = request.data.pop('Vorname') request.data['lastname'] = request.data.pop('Nachname') serializer = NameSerializer(data=request.data) if serializer.is_valid(): print(serializer.data) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So as I said this already works with using dict.pop() to transform the request.data dictionary. But what I would want it to do is to … -
how can i get queryset based on mapping table in django rest framework?
models.py class MasterCategory(models.Model): name = models.CharField(max_length=200, blank=True, null=True) code = models.CharField(max_length=20, blank=True, null=True) icon = models.TextField(blank=True, null=True) image = models.TextField(blank=True, null=True) is_active = models.BooleanField(default=True, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'master_category' class MasterLessonType(models.Model): lesson_type = models.CharField(max_length=20, blank=True, null=True) lesson_code = models.CharField(max_length=20, blank=True, null=True) is_active = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'master_lesson_type' class Lesson(models.Model): lesson_type = models.ForeignKey(MasterLessonType, on_delete=models.CASCADE, blank=True, null=True) content = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = "lesson" ** --- category can be mapped to multiple lesson -----** class CategoryLessonMapping(models.Model): category = models.ForeignKey(MasterCategory, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'category_lesson_mapping' ** ---- user can be mapped sto multiple lesson --- ** class UserLessonMapping(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True) class Meta: db_table = 'user_lesson_mapping' I want to get the logged in user, user mapped to lesson, lesson mapped to category and lesson mapped to lesson type data like this { user:{ 'id':1, 'first_name': 'alan' 'last_name': 'walker' }, 'lesson': [ { "id": 1, "lesson_type": { "id": 1, "lesson_type": "Video", … -
Making a request that triggers a function that searches a json object. The object will be updated every minute, could this lead to issues?
I am making a bus prediction web application for a college project. The application will use GTFS-R data, which is essentially a transit delay API that is updated regularly. In my application, I plan to use a cron job and python script to make regular get requests and write the response to a JSON file, essentially creating a feed of transit updates. I have set up a get request, where the user inputs trip data that will be searched against the feed to determine if there are transit delays associated with their specific trip. My question is - if the user sends a request at the same time as the JSON file is being updated, could this lead to issues? One solution I was thinking of is having an intermediary JSON file, which when fully loaded will replace the file used in the search function. I am not sure if this is a good solution or if it is even needed. I am also not sure of the semantics needed to search for solutions to similar problems so pointers in the right direction would be useful. -
How to make a shortcut of day display e.g Thursday 14/07/2022 => Thu 14/07/2022 in Django html template
I have booking start date as follow <p>{{ booking.start_time|date:"j/F/Y" }}</p> on Django html template which it displays the date as 14/July/2022 on the DOM, how I can make it display like this Thu 14/07/2022 -
How to return 400 status code from custom middleware in django?
I am trying to write a custom middleware which does some operation on the request to check its validity and if the request is invalid then return the bad request 400 status code without even going ahead. from django.http import HttpResponseBadRequest class VersionCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): meta = request.META client = meta.get('HTTP_X_APP_CLIENT', None) if client == 'ios': app_version = ( int(meta['HTTP_X_IOS_APP_VERSION']) if meta.get('HTTP_X_IOS_APP_VERSION') else int(meta.get('HTTP_X_APP_VERSION', 0)) ) if app_version < 30: return HttpResponseBadRequest elif client == 'android': app_version = int(meta['HTTP_X_APP_VERSION']) if app_version < 188: return HttpResponseBadRequest elif client == 'web': app_version = int( meta['HTTP_X_APP_PLATFORM_VERSION'] if meta.get("HTTP_X_APP_PLATFORM_VERSION") else meta['HTTP_X_APP_VERSION'] ) if app_version < 188: return HttpResponseBadRequest response = self.get_response(request) return response -
how to add value from user input field in django imoirt-export library?
I have model named Product and Calculator that is connected to each item in Product model. What I am trying to achieve is to allow user to insert number of units and based on this number calculate total price in Excel file that will be exported when user clicks Calculate button. Questions: How can I add value inserted by a user in my input field to my cost_calculator.xlsx file and based on that value calculate total price? How can I add unit_hours property from CostCalculator model to my exported file? I successfully added it to admin page and it shows me correct result but when I add to to fields in my resource model then I get KeyError. What is the best approach to calculate total_price and display it in Excel in my case? The formula is following: number_of_units * rate * margin = total_price. Should I put it in form_valid in ProductDetailView or in ExportData view or maybe I shouldn't seperate Export button to seperate view but add it to form_valid. Is it possible to merge Send and Calculate buttons into one so if user clicks 1 button it will send user's value, calculate and export unit_hours and total_price … -
How do I change the default value of a field on a bound form that gets rendered in Django?
In a Django project we have forms that have already been submitted where for some reason the person before me set the default value of a field to be one blank space (' ') and this is affecting some other functionality where we need to copy data (not relevant to go into detail for this question I don't think) Anyway, here is a snippet from models.py where I changed the default value to '': #inside class Meta base64_encoded_activation_key = models.CharField (max_length = 1000, default = '', blank = True, verbose_name = 'Activation Key') Inside views.py def edit_activation(request, id=None): ...... activation = get_object_or_404(ActivationRecord, pk=id) ....... ....... ....... else: # GET request form = ActivationRecordForm(instance=activation) Now, this works fine if I create and submit a new form, but when I go back to an old form then the value is still ' ' (which I guess is expected as the form has been submitted) but I don't know how to fix this to the new default value.