Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Can I get Monthly Income, Expenditure, Net Income and display in django Template using a loop
I am working on Django project with two models; Expenditure and Income. I want to get Total Income, Total Expenditure, and Net Income for each month displaced in a table. The Net Income should be Total Income minus (-) Total Expenditure. And here I have this models (Income and Expenditure are same) are having the same properties as shown below. class Income(models.Model): description = models.CharField(max_length=100, null=False) category = models.CharField(max_length=100, choices=CATEGORY_INCOME, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) remarks = models.CharField(max_length=120, null=True) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) Here what I have tried in my views file: def monthly_Income(request): total_monthly_income = Income.objects.annotate(month=TruncMonth('date')).values('month').annotate(total_monthly_income=Sum('amount')) total_monthly_expenses = Expenditure.objects.annotate(month=TruncMonth('date')).values('month').annotate(total_monthly_expenses=Sum('amount')) net_monthly_income = total_monthly_income - total_monthly_expenses context = { 'total_monthly_income': total_monthly_income, 'total_monthly_expenses':total_monthly_expenses, 'net_monthly_income':net_monthly_income' } In my django Template this is how I am trying to display the results. {% for income in total_monthly_income %} {{ income.total_monthly_income | intcomma }} {{ total_monthly_expenses }} {{ net_monthly_income }} {% endfor %} The problem here is that, I am able to get the total monthly income but not able to get the total monthly expenses and net income according to each month of the year. Someone should kindly assist me get the right result accordingly. -
Django how to solve UnicodeEncodeError: 'charmap'?
I am trying make my project multilanguage. I install rosetta. When I write django-admin makemessages -l tr, console gives an error: (myvenv) C:\Users\USER\OneDrive\Documents\GitHub\otc>django-admin makemessages -l tr UnicodeDecodeError: skipped file QuickStartClientCom.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x96 in position 1724: invalid start byte) UnicodeDecodeError: skipped file QuickStartServerCom.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x92 in position 2291: invalid start byte) UnicodeDecodeError: skipped file docindex.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x92 in position 1113: invalid start byte) UnicodeDecodeError: skipped file misc.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x92 in position 407: invalid start byte) UnicodeDecodeError: skipped file package.html in .\myvenv\Lib\site-packages\win32com\HTML (reason: 'utf-8' codec can't decode byte 0x85 in position 2807: invalid start byte) Traceback (most recent call last): File "C:\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\USER\OneDrive\Documents\GitHub\otc\myvenv\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\commands\makemessages.py", line 382, in handle potfiles = self.build_potfiles() File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\commands\makemessages.py", line 424, in build_potfiles self.process_files(file_list) File "c:\users\user\onedrive\documents\github\otc\myvenv\lib\site-packages\django\core\management\commands\makemessages.py", … -
Supplying remote JSON data for Typeahead / Bloodhound with Django / Python
I'm trying to replicate functionality of this Typeahead remote example, but I can't figure out how to supply the data in the way Typeahead / Bloodhound wants it, nor what datumTokenizer or queryTokenizer are for. In Python / Django views.py I've got: nouns = ['apple', 'banana', 'pear'] return JsonResponse({'results': noun_results}) reaching the site as: {"results": ["apple", "banana", "pear"]} Yet for 'kings' the example returns: [{"year": "1949","value":"All the Kings Men","tokens":["All","the","Kings","Men"]}] Need we return it in this format? If so, how? How can we make a simple replication of the example? -
PasswordChangeView Doesn't Show Success Message in Django
I have tried some different things on this PasswordChangeView but still couldnt show the right success message even with SuccessMessageMixin The messages works but not after clicking submit button it shows message after you come back again to password change url and shows blank password change form with success message. What i want to achive is i want to show message to user when he/she clicks after submit button. Probably answer is pretty easy but i am newbie and don't know how to handle this error and success messages in forms for now. Everything works Perfect Changes password and redirects after sleeping 1 second. Thanks For all help. class PasswordChange(SuccessMessageMixin,PasswordChangeView): model = User form_class = PasswordChangeForm template_name = "passwordchange.html" success_message = "Password Changed Successfully You will be redirected in 1 second" success_url = reverse_lazy("password_change_done") class PasswordDone(PasswordChangeDoneView): template_name = "password_change_done.html" def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: sleep(1) return redirect("posts") return super(PasswordDone,self).dispatch(request, *args, **kwargs) -
Lowercase Field values django models queryset
I have a Model of an object and few tags are assigned to the object of this model. Tags may be uppercased, lowercased or mix of both cases. I want to write a queryset which will return those object which has same tags which I provided. Note: I am using django-taggit module. Views.py def home(request): book = Book.objects.filter(tags__name__in= map(lambda s:s.lower(), ['harry-potter', 'Champak', 'Physics'])) print(book) return HttpResponse("Books Retrieved") Models.py from django.db import models from django.utils.translation import ugettext_lazy as _ from taggit.managers import TaggableManager from taggit.models import GenericUUIDTaggedItemBase, TaggedItemBase class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase): class Meta: verbose_name = _("Tag") verbose_name_plural = _("Tags") class Book(models.Model): name = models.CharField(max_length=100) details = models.TextField(blank=True) tags = TaggableManager(through=UUIDTaggedItem, blank = True) Now I want to return all the books which have tags mentioned as 'HArry-Potter', 'HARRY-POTTER', or any other word. PS: If anyhow we can lower the 'tags__name__in' List, our work will be done. -
graphene_django DjangoFilterConnectionField - The type * doesn't have a connection
I have a problem with graphene_django. When I create a DjangoObjectType and pass this to DjangoFilterConnectionField in my Query, I get an AssertionError that The type {my DjangoObjectType class} doesn't have a connection. Here is part of my code: class TradeType(DjangoObjectType): class Meta: model = Trade filter_fields = { 'id': ['exact', 'range', 'in', 'gte', 'lt'], 'updated': ['gte', 'lt'], 'created': ['gte', 'lt'] } interface = (graphene.relay.Node,) class Query(graphene.ObjectType): trades = DjangoFilterConnectionField(TradeType) I did all of this based on this page. graphene==2.1.9, graphene_django==2.15, django-filter==2.4 -
NippleJS angle is wrong upon page reload
While trying to use the code from https://github.com/yoannmoinet/nipplejs, a click is registered in the forward direction by default . When the page is reloaded, the click becomes registered in the backward direction by default, is there a way to change this? -
Try to put an input in graph function Django with Matplotlib
I am making a code that graphs user given functions with Django. I have used numpy and matplotlib libraries, and the code works fine, it does its job if I do it with burned code, but when I want to pass it to the user data, it fails, any idea how I can do it? Funcion import matplotlib.pyplot as plt import numpy as np def Graficador(request): x = symbols('x') t = np.arange(-10.0, 10.0, 0.010, ) s = (request.POST['funcion']) s = parse_expr(s) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() g = mpld3.fig_to_html(fig) fig.savefig("test.png") context = {'g': g} return render(request, 'Graficar.html', context) Html {% autoescape off %} <div>{{ g }}</div> {% endautoescape %} -
Django ASGI and WSGI Deploying Together
The application I developed using Django includes WSGI and ASGI applications together. What kind of way do I need to follow while deploying this application? In general, when I searched on the internet, I could not find anythig that deployed WSGI and ASGI applications together. what is a way to accomplish this? -
GeoDjango saving empty fields
Alright, why is it that I can't save empty values to a Point-, MultiPoint- or PolygonField? I created a form where users can select an area or location where they spotted a specific bird species. To store the data I use GeoDjango, the data can be stored in a PointField or PolygonField. The PointField however is not required, so in the forms I set required to False which gives me the following error; For the record, I am using MySQL as a database. I currently don't need all the extra features PostgreSQL comes with. IntegrityError at /sighting/where-did-you-spot-the-bird/ (1048, "Column 'sighting' cannot be null") #models.py from django.contrib.gis.db import models class Sighting(models.Model) name = models.CharField(max_length=140) description = models.TextField() sighting = models.PointField( blank=True, null=True, spatial_index=False ) So the column sighting cannot be null, why is that? Am I missing something or is a value always required? One solution would be to save a default value, let's say Point(0,0) but their should be another solution. Any ideas would be much appreciated! -
Pytest-django transaction is not commited to DB physically
There is a conftest.py file that allows me to use my custom transactional fixture fake_user @pytest.mark.django_db(transaction=True) @pytest.fixture def fake_user(): user = getattr(fake_user, 'user', None) if user is None: user_data = dict( id=1, is_superuser=False, is_staff=False, email='foo@barmail.com', username='foobaruser', password='passwordmaster', date_joined=timezone.now() ) user = User.objects.create( **user_data ) user.save() # pdb.set_trace() fake_user.user = user yield user Somehow if I debug with pdb.set_trace() the code above, I get User.objects.all() equal to <QuerySet [<User: foobaruser>]>. However there are no any real test DB records. So when querying "User" objects in another high level function, e.g. "GraphQL" or REST call, I get "Users" table being absolutely empty. How could I enable real test DB transactions? Why does't pytest allow any physical records or what prevents them from being inserted? -
How to get foreignkey field value in django?
I have two model given below: class Color(models.Model): colorName = models.CharField(max_length=200, null=True, blank=True) # _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.colorName) class Variant(models.Model): product = models.ForeignKey(Product, on_delete= models.CASCADE, null=True,blank=True) color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(null=True, blank=True) def __str__(self): return str(self.product) views.py @api_view(['GET']) def getProduct(request, pk): product = Product.objects.get(_id=pk) variants = Variant.objects.filter(product=product) productserializer = ProductSerializer(product, many=False) variantserializer = VariantSerializer(variants,many=True) data = {'product_details':productserializer.data,'product_variants':variantserializer.data} print(data) return Response(data) here color field return colorName field's id but I need colorName field's value How to solve this? -
How to use objects specified by a manager instead of the default objects in a class based or function view?
My code: models.py class EmployeeManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(employed=False) class NotEmployedEmployee(models.Manager): def get_queryset(self): return super().get_queryset().filter(employed=False) class Employee(models.Model): objects = EmployeeManager() not_employed = NotEmployedEmployees() name = models.CharField(max_length=250) employed = models.BooleanField(default=True, blank=True, null=True) views.py class EmployeeListView(ListView): model = Employee template_name = 'tmng/employee_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) resultset = EmployeeFilter(self.request.GET, queryset=self.get_queryset()) context['filter'] = resultset return context class EmployeeUpdateView(UpdateView): template_name = 'tmng/employee_update.html' model = Employee fields = '__all__' def form_valid(self, form): self.name = form.cleaned_data.get('name') return super().form_valid(form) def get_success_url(self): messages.success(self.request, f'Employee "{self.name}" changed!') return '/' For all my currently working employees my list and update view works fine. But I also want a list/update-view for my not-employed employees so I can 'reactivate' them ones they rejoin the company. For the list view I found a semi-solution by using a function based view. views.py def not_employed_employee_list_view(request, *args, **kwargs): template_path = 'tmng/employee_not_employed.html' context = {'employees': Employee.not_employed.all()} return render(request, template_path, context) So what I'm looking for is way to see list/update non employed employees. Is there way to say to class based / functions views to use not the default employees but the 'non_employed' employees? -
Django ORM Count Without Duplicate Column
I have a table called Reading History. I want to find the average number of reads in this table. I wrote the following method for this, but I can't get the right result. Records are made in the table once (student-book records with the same values). When the same record comes, the counter value is increased by one. For example, suppose that two different students read two different books. I expect total reads / 2 but the result I get is total reads / 4 because there are 4 rows in the table. How can I calculate this? For example, if a student reads 4 different books once, the average will be 1, but the average should be 4. I tried to use distinct and values but I couldn't get the result I wanted. Maybe I didn't manage to use it correctly. Also I tried to use Avg. When avg didn't give the correct result, I tried to break it down and get the values myself. Normally, Avg was written in Sum. Serializer class ClassReadingHistoryReportSerializer(ModelSerializer): instructor = InstructorForClassSerializer(source="instructor.user") students = StudenListReadingHistoryReportSerializer(many=True, source="student_list_class") avg_read_book = serializers.SerializerMethodField() class Meta: model = Class exclude = [ "created_at", "updated_at", "school", ] def get_avg_read_book(self, obj): … -
Importing data into a 2D array from MSSQL database
I am trying to print a trial balance through a web app. The app currently prints the description but not in a line by line format, I have had a look at the .filter function but I don't know how that would translate to MSSQL queries. If anyone one has any examples for me , that would be a great help. Views.py : def home(request): query = "SELECT Description ,Account, Debit , Credit FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" desc = "SELECT Description FROM [Kyle].[dbo].[_btblCbStatement] WHERE Account <> ''" cursor = cnxn.cursor(); cursor.execute(desc); description = cursor.fetchall() return render(request , 'main/home.html' , {"description":description}) Home.html: {% extends "main/base.html"%} {% block content%} <h1>HOME</h1> {% for description in description %} <div class="row mb-3"> <div class="col"> <p>{{ description }}</p> </div> {% endfor %} </div> {% endblock %} Output: -
Django allauth problem with setting sessions params and getting them after login
I am using Django allauth to associate already logged in in Django users with their social accounts. For frontend I use Vue js, it sends in body pw and username. My idea was to save Django user id in session parameters after login and grab it back during the allauth flow. As far as I understood it should work: Passing a dynamic state parameter using django-allauth during social login However, by some reason when I am trying to access the session parameter in allauth flow it is empty. The id is set in session and it should be fine. Currently, it is tested on Google OAuth2. My login view: @api_view(('POST',)) def login_user(request): # get credentials from Body request_data = json.loads(request.body) print(request_data) # DEBUG username = request_data['username'] password = request_data['password'] try: # get user instance if not User.objects.filter(username=username).exists(): raise ValidationError("The user does not exist") else: if username and password: # authenticate user user = authenticate(username=username, password=password) if not user: raise ValidationError("Incorrect password or username") if not user.is_active: raise ValidationError("This user is no longer active") print(user) # DEBUG # set session cookie with user id print('SESSION UID', user.id) request.session['user_id'] = user.id # works session_uid = request.session.get('user_id', 'LOGIN NO SESSION UID') # get … -
how to edit, delete row data in one page using django table
I am using Django and I am outputting data to a Table . Modification and deletion of each row implemented the function by passing the argument as the url parameter of the detail page of each row. I want to edit and edit the table itself, which outputs the entire row without going into the detail page. (The detail page is redirected by the table-link function implemented when each row is clicked.) <table id="waitinglist-list-table"> <thead> <tr> <th>name</th> <th>age</th> <th>weight</th> <th>register_date</th> <th>Edit</th> <th>Remove</th> </tr> </thead> <tbody> {% for register in register_list %} <tr class="tr-hover table-link" data-link="/register/detail/{{ register.id}}/"> <td>{{ register.name}}</td> <td>{{ register.age }}</td> <td>{{ register.weight}}</td> <td>{{ register.register_date }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#edit_register">Edit </button> </td> <td> <button data-toggle="modal" data-target="#remove_register" type="button" id="register-remove-button" register-id="{{ register.id }}" class="btn btn-inverse-danger">Remove </button> </td> </tr> {% endfor %} </tbody> </table> In the past, when editing and deleting, the id was requested in the url parameter. def edit_register(request, id): register = Register.objects.get(pk=id) edited_register, errors = Register.register_form_validation(request) if errors: return JsonResponse({'code': 'error', 'error': errors}) register.name = edited_register.name register.age = edited_register.age register.weight = edited_register.weight register.register_date = edited_register.register_date register.save() return JsonResponse({'code': 'success'}) def delete_register(request, id): register= Register.objects.get(pk=id) register.is_deleted = True register.save() return HttpResponseRedirect(f'/register/') Do you need a way to receive … -
modal opening only for the first for loop element?
I have my for loop in django such as its only opening the modal for the first element and nothing happens for other elements? : This is my html file it display all elements in a table with delete button. When clicking delete button a modal is opened but it is opened for the first element only? what should i change in this? <table> {% for card in cards %} <tr class="record"> <td>{{card.number}}</td> <td> <button class="hover:bg-gray-500 duration-500" id="delete-btn" > </button> <div class=" fixed flex justify-center items-center hidden " aria-labelledby="modal-title" aria-modal="true" id="overlay" > ............. #some lines of code <div class=" bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse " > <a href="{% url 'p:delete-card' card.id %}" id="delbutton" > <button type="button" class=" w-full inline-flex justify-center " > Delete </button> </a> </div> </div> </div> </td> </tr> {% endfor %} my js to open the modal on button click: window.addEventListener('DOMContentLoaded',() =>{ const overlay = document.querySelector('#overlay') const delbtn = document.querySelector('#delete-btn') const toggleModal = () => { overlay.classList.toggle('hidden') overlay.classList.add('flex') } delbtn.addEventListener('click',toggleModal) }) call url on clicking delete button: $(document).on("click","#delbutton" ,function(e){ e.preventDefault(); var $this = $(this); $.ajax({ url: $this.attr("href"), type: "GET", dataType: "json", success: function(resp){ $this.parents(".record").fadeOut("fast", function(){ $this.parents(".record").remove(); window.location.reload(); }); } }); return false; }); -
How do I get the orignal name of the file that is uploaded in the filefield in django
I want to access the name of the file uploaded to models.FileField() in my class. Here is my class class extract(models.Model): doc = models.FileField(upload_to='files/') Is there a function or some method, to access the original name of the uploaded file, without modifying the name during upload. like something like this name = doc.filename() -
Django urls points wrong path
I'm writing a production machines management application and I've encountered a strange problem that I can't solve. Previously, I had a "Transactions" subpage with paths under the description with the same name. Everything was working very well. Today I tried to add another sub-page, "Transactions per person" and the problem starts. # Transaction path('transaction/machines', views.transaction_machines_list_view, name="transaction_machines_list"), path('transaction/machine/<int:id>', views.transaction_list_view, name="transaction_list"), # Transaction per-Capita path('per_capita/employees', views.transaction_per_capita_employees_list_view, name="transaction_per_capita_employees_list"), path('per_capita/employee/<int:id>', views.transaction_per_capita_list_view, name="transaction_per_capita_list"), All "transaction" paths works well, per_capita/employees works well too but when I try to reach the last one, for example http://127.0.0.1:8000/per_capita/employee/2 I encounter the following error NoReverseMatch at /per_capita/employee/2 Reverse for 'transaction_list' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['transaction/machine/(?P<id>[0-9]+)$'] Why is my path named transaction_per_capita_list received as transaction_list by Django? The redirect itself is a row in the table and looks like this: <tr class="pointer" onclick="location.href='{% url 'transaction_per_capita_list' id=employee.id %}';"> <td class="cell">{{ employee.username }}</td> <td class="cell">{{ employee.first_name }}</td> <td class="cell">{{ employee.last_name }}</td> </tr> I've tried changing the path, I've tried renaming it and it doesn't do anything. What am I doing wrong? -
Django - Extract hash tags from a post and save them all in a many-to-one relation
So I have this code below that when a user submits a post it extracts all the hash tags from it then creates a new entry in the hash tag table and also creates a new reference in the HashTagsInPost table so people can search posts by hash tags. My primary concerns lay in the Views.py file. Problems: I don't think it's good to iterate over the list of hash tags pulled out and doing a .get() call to see if exists then if it doesn't create it. There should be a better way to do this. Since HashTagsInPost is a one-to-many relation, I don't really know how to store that lists of Hash Tags as the hash_tag attribute in the HashTagsInPost attribute. Do I just pass a list of HashTag objects? Views.py def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): post_body = request.data['body'] post_obj = serializer.save() hash_tags_list = extract_hashtags(post_body) for ht in hash_tags_list: try: ht_obj = HashTags.objects.get(pk=ht) except HashTags.DoesNotExist: ht_obj = HashTags.objects.create(hash_tag=ht) HashTagsInPost.objects.create(hash_tag=ht_obj, post_id=) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Models.py class HashTags(models.Model): hash_tag = models.CharField(max_length=140, primary_key=True) class Post(AbstractBaseModel): creator_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_creator_id", db_index=True) goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE, db_index=True) body = models.CharField(max_length=511) class HashTagsInPost(AbstractBaseModel): hash_tag = models.ForeignKey(HashTags, … -
How to manually customize parameters of DRF views using drf-yasg Swagger?
I am using drf-yasg package to integrate Swagger with DRF. As documentation said I used @swagger_auto_schema decorator to manually customize auto-generated endpoints. After a lot of tries I still can't figure out why there are no any changes. So, I tried to add extra query parameter to RetrieveUpdateAPIView: class MyCustomView(RetrieveUpdateAPIView): ... @swagger_auto_schema( manual_parameters=[openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN)] ) def retrieve(self, request, *args, **kwargs): ... After all, nothing seems changed. What exactly I have to do then? -
How to find the right "gas" value in order to send a transaction on Ropsten testnet?
I'm a newby in the Web3/Ethereum world and I'm trying to build an app that can simply write a block onto the Ropsten testnet through Infuria. Unfortunately the following code seems not to work from web3 import Web3 def sendTransaction(message): w3 = Web3( Web3.HTTPProvider( "https://ropsten.infura.io/v3/my_project_id" ) ) address = "https://ropsten.infura.io/v3/my_project_id" privateKey = "my_private_key" nonce = w3.eth.getTransactionCount(address) gasPrice = w3.eth.gas_price value = w3.toWei(1, "ether") signedTx = w3.eth.account.sign_transaction( dict( nonce=nonce, gasPrice=gasPrice, gas=1000000000, to="0x0000000000000000000000000000000000000000", value=value, data=message.encode("UTF-8"), ), privateKey, ) tx = w3.eth.sendRawTransaction(signedTx.rawTransaction) txId = w3.toHex(tx) return txId In particular the field gas seems to create problems. If I add too much zeroes, I'll get the error message 'exceeds block gas limit', whereas with less zeroes the error message becomes 'insufficient funds for gas * price + value'. -
Do you need a csrf token for a get request in Django templates?
Do you need a csrf token for a get request in Django? I know that you need one for a post request like the template below: <form method="post" class="mt-5"> {% csrf_token %} {{ form|crispy }} <button type='submit' class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md"> Update </button> </form> However, I don't know if I need one for a get request like below: <form method="GET" action="."> <div class="form-row"> <div class="form-group col-12"> <div class="input-group"> <input class="form-control py-2 border-right-0 border" type="search" name="title_contains" placeholder="Title contains..." /> <span class="input-group-append"> <div class="input-group-text bg-transparent"> <i class="fa fa-search"></i> </div> </span> </div> </div> </div> </div> <button type="submit" class="btn btn-primary">Search</button> </form> I don't want my get request being vulnerbale to attackers, but I don't know if it is okay to add a csrf_token like the one for post request. If you have any questions, please ask me in the comments. Thank you. -
How can i update a specific field using foreign key relationship
I want to update a field which is called level. My relation is like this. i am using django User model. Which is extended to Extended user like this below:- class ExtendedUser(models.Model): levels_fields = ( ("NEW SELLER", "NEW SELLER"), ("LEVEL1", "LEVEL1"), ("LEVEL 2", "LEVEL 2"), ("LEVEL 3", "LEVEL 3") ) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(null=True, unique=True) contact_no = models.CharField(max_length=15, null=True) profile_picture = models.ImageField(upload_to="images/", null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) level = models.CharField(max_length = 120, null=True, blank=True, choices=levels_fields, default="NEW SELLER") I have a field call "Level" which is full of choices. Now i have a model named Checkout This is the checkout model :- class Checkout(models.Model): ORDER_CHOICES = ( ("ACTIVE", "ACTIVE"), ("LATE", "LATE"), ("DELIVERED", "DELIVERED"), ("CANCELLED", "CANCELLED"), ) user = models.ForeignKey(User, on_delete=models.CASCADE) seller = models.ForeignKey( User, on_delete=models.CASCADE, null=True, related_name='seller') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) package = models.ForeignKey(OfferManager, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0) price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) total = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) grand_total = models.DecimalField( decimal_places=2, max_digits=10, default=0.00, null=True) paid = models.BooleanField(default=False) due_date = models.DateField(null=True) order_status = models.CharField(max_length=200, choices=ORDER_CHOICES, default="ACTIVE") is_complete = models.BooleanField(default=False, null=True) I have another model which is called SellerSubmit and the checkout is the foreign …