Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - BooleanField - checkbox
I'm working on a web app. This web app should let people add links to a list and then press a button to open all the links at once. So far I have this: Each link can be set to either True or False, when I clink on 'open links' only the links that are set to True will open. Now, I would like to add a checkbox next to 'Delete link'. When the checkbox is ticked the value will be True and when I untick the checkbox the value will change to False. Any help will be much appreciated, thank you! My code so far: models.py from django.contrib.auth.models import User class Site(models.Model): """A site that will be opened""" name = models.CharField(max_length=200) link = models.URLField(max_length=200) selected = models.BooleanField(default=True) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return self.name forms.py from .models import Site class SiteForm(forms.ModelForm): class Meta: model = Site fields = ['name', 'link', 'selected'] labels = {'name':'Name','link': 'Link', 'selected': 'Selected'} urls.py from django.urls import path from . import views app_name = 'links' urlpatterns = [ # Home page. path('', views.index, name='index'), # Show all links. path('links/', views.links, name='links'), # Page for β¦ -
Django not saving all data passed via POST
I am trying to save request.POST in the model but unfortunately - i am not getting all data saved. For fields "carrier" and "spot" - when i render a template it shows me None altough in QueryDict in command prompt i am seeing both values passed. code from command prompt (when POST is printed) <QueryDict: {'csrfmiddlewaretoken': ['38kuFlpIUMbmwXJ77qKaz2wWPOuqnM1IaYpKZdmaFVdEmVcuuu7hzf0wr0fEEO8o'], 'currency': ['USD'], 'pickup': ['1'], 'origin_cust': ['1'], 'origin_hand': ['11'], 'airfreight': ['234'], 'dest_cust': ['234'], 'dest_hand': ['234'], 'delivery': ['32'], 'screening': ['342'], 'dgfee': ['342'], 'Submit': ['Submit'], 'carrier': [1], 'spot': [1]} views.py def offer_spot(request): my_p = Stakeholder.objects.get(user=request.user) print(my_p) form = OfferForm() if request.method == 'POST': request.POST._mutable = True request.POST['carrier'] = my_p.pk request.POST['spot'] = 1 print("print", request.POST) form = OfferForm(request.POST) if form.is_valid(): form.save() return redirect('/offers') else: print(form.errors) context = {'form': form} return render(request, 'spotrequesting/offer_spot.html', context) models.py class Offer(models.Model): currency = models.CharField( validators=[RegexValidator(regex='[A-Z]{3}', message='Currency is three letters')], max_length=3,null=False) pickup = models.FloatField(default=0) origin_cust = models.FloatField(default=0) origin_hand = models.FloatField(default=0) airfreight = models.FloatField(default=0) dest_cust = models.FloatField(default=0) dest_hand = models.FloatField(default=0) delivery = models.FloatField(default=0) screening = models.FloatField(default=0) dgfee = models.FloatField(default=0) carrier = models.ForeignKey(Stakeholder,null = True,on_delete=models.CASCADE) spot = models.ForeignKey(Spot,null = True,on_delete=models.CASCADE) What is strange - when i type "default = 1" in Offer model for both Foreign Keys - application is saving what is really under β¦ -
How to access a list in a dictionary in django template
I build a dictionary that contain a list. I want to access the list in my django template by index I access my dictionary with a custom tag @register.filter(name='keyvalue') def keyvalue(dict, key): return dict[key] and in html {% for p in participant %} <tr> <td>{{ p }}</td> <td>{{p.eMail}}</td> <td>{{p.participantNationality}}</td> <td>{{p.participantStreet}} {{p.participantStreetNumber}}, {{p.participantZipcode}}, {{p.participantCity}} </td> <td>{{p.participantCountryResidency}}</td> <td>{{p.participantSpecialNeeds}}</td> <td>{{p.participant_fee_no_reduction}}β¬</td> <td> <p style="line-height : 10px">{{discounts|keyvalue:p.pk}}</p> </td> {% if totalAmount == 0 %} <td>Free</td> {% else %} <td>{{p.participantFee}}β¬</td> {% endif %} </tr> {% endfor %} The code like that work, it return the right list for the right participant except that its a plain python list. I want to access the values in the list by index. When i try {{discounts.discount_list.1|keyvalue:p.pk}} i have string index out of range as the list is considered like a string. Any idea how to do it ? Thanks -
How to pass a location path to the imagefield in django model?
I want to save the image in the imagefield of my model by passing the location of the image. My serializer: class UserModelSerializer(serializers.ModelSerializer): password = serializers.CharField() confirm_password = serializers.CharField() class Meta: model = User fields = ['image','email','fullname','dob','phonenumber','passportnumber','username','password','confirm_password'] My Model: class CustomUser(AbstractUser): image = models.ImageField(upload_to='images/',blank=True,null=True) email = models.EmailField(_('email address'), unique=True) fullname = models.CharField(null=True,max_length=40) dob = models.DateField(default=date.today) phonenumber = models.CharField(max_length=10, blank=True) passportnumber = models.CharField(max_length=10, blank=True) My View: class UserRegistrationAPIView(generics.CreateAPIView): serializer_class = UserModelSerializer permission_classes = [permissions.AllowAny] renderer_classes = [TemplateHTMLRenderer] # renderer_classes = [JSONRenderer] template_name = 'accounts/api_register.html' def get(self, request): serializer = UserModelSerializer() print("Reaching Get") # return Response({'serializer':serializer.data}) return Response({'serializer': serializer}) def post(self, request): draft_request_data = request.data.copy() # print(draft_request_data.image) # print("**********************") # print(type(draft_request_data)) #print(draft_request_data) #draft_request_data.pop('image') #draft_request_data.pop('confirm_password') print(draft_request_data) serializer = self.get_serializer(data = draft_request_data) print(serializer.is_valid()) if not serializer.is_valid(): print(serializer.errors) return Response({'serializer': serializer}) # print("serializer+++++++++++++++") # print(serializer.data.pop('confirm_password')) # print(serializer) serializer.save() return redirect('/login/') The data which I passed to the serializer is : <QueryDict: {'csrfmiddlewaretoken': ['72YZOX1hiXdcBMjp5wTAv8WNwLNjC8ebUPVNihiQwdsZn7wmSoEBMFQEWR3a5Lpx'], 'image': ['images/Screenshot from 2020-07-26 21-30-52.png'], 'email': ['ran@gmail.com'], 'fullname': ['ran'], 'dob': ['1995-11-06'], 'phonenumber': ['7395905243'], 'passportnumber': ['SIFNFHK'], 'username': ['ran'], 'password': ['Singo1995'], 'confirm_password': ['Singo1995']}> As you can see I am passing the image location to the image key as /images/Screenshot from 2020-07-26 21-30-52.png This is where the problem occurs the serializer.is_valid() in views.py transforms the β¦ -
How to get a value in a database and display on django form
I have a DuesLevy model with a field called user which happen to be a foreign key to my User model. I want to display email value from the User model to my form AddMemberDuesForm() The reason is this I want to get the email and amount value and pass it to my payment processor. I am using class based views to process my form below is my code forms.py class AddMemberDuesForm(forms.ModelForm): class_of_dues = forms.CharField(required=False, widget=forms.Select(choices=options.CLASS_OF_DUES, attrs={'class':'form-control'})) payment_circle = forms.CharField(required=False, widget=forms.Select(choices=options.PAYMENT_CIRCLE, attrs={'class':'form-control'})) payment_option = forms.CharField(required=False, widget=forms.Select(choices=options.PAYMENT_OPTION, attrs={'class':'form-control'})) payment_channel = forms.CharField(required=False, widget=forms.Select(choices=options.PAYMENT_CHANNEL_TYPE, attrs={'class':'form-control'})) amount = forms.DecimalField(widget=forms.NumberInput(attrs={'class':'form-control'})) payment_date = forms.DateField(widget=forms.DateInput(attrs={'class':'form-control', 'type':'date'})) description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control'})) class Meta(): model = DuesLevy exclude = ('date_recorded', 'start_date', 'end_date', 'transaction_id') views.py class AddMemberDues(LoginRequiredMixin, CreateView): login_url = '/backoffice/' model = DuesLevy template_name = 'dashboard/add-edit-member-dues.html' form_class = AddMemberDuesForm context_object_name = 'member_form' def post(self, request, *args, **kwargs): form = AddMemberDuesForm(request.POST) if form.is_valid(): form = AddMemberDuesForm() form.user.email = form.user.cleaned_data['email'] self.template_name = 'dashboard/payment.html' form.save() return render(request, self.template_name, {'email': form.cleaned_data['email'], 'amount': form.cleaned_data['amount']}) def get(self, request, *args, **kwargs): initial = {'email':request.user.email} form = AddMemberDuesForm(initial=initial) return render(request, self.template_name, {'email': form.cleaned_data['email']}) I get this error in the 'AddMemberDuesForm' object has no attribute 'cleaned_data' Internal Server Error: /backoffice/add-member-dues/ Traceback (most recent call last): File "C:\Users\Benedict\Miniconda3\envs\mycda\lib\site-packages\django\core\handlers\exception.py", line 34, β¦ -
How do you handle video in Django for elearning site
I am a learner in django and i have been trying to create a paid elearning site , the problem comes to handling the video courses , all i have got from research on Youtube and tutorials is if you host the courses locally someone can go directly to the url and get the resource .I need help on the way to do it -
How to Send CSRF token to ajax request Using Django?
i Want to Send csrf token in Ajax Request in Django.i don't know how to do that .i have following Code. in My html File, i am having one button <div class="col-md-6 col-sm-12 text-right" id="button_div"> <a href="#" id="add_data" class="btn btn-primary">Add</a> </div> <div id="dynamic_table"> /*some html*/ </div> When i Click on "Add" button,i Empty "dynamic_table" and i Append my contact form code into "dynamic_table" div. Contact Form code is <form> <input type="text" name="fname"> <input type="text" name="lname"> <input type="button" name="send" value="send"> </form> for that i am Using following Code $(document).on('click','#add_ajax',function(){ $("#dynamic_table").empty(); $("#dynamic_table").append('<form><input type="text" name="fname"><input type="text" name="lname"><input type="button" name="send" id="form_save" value="send"></form>'); }); till now, its working fine but When i CLick on "form_save" button from my contact form $(document).on('click','#save_btn',function(){ alert('hello') }) i am Getting following Error Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST β¦ -
matching query does not exist , Django error
** Item matching query does not exist.** -
Django Self Foreign Key......why we need to use them?
I have a question.i have seen people tend to use "self foreign-key" while structuring hierarchy , like, Category > Sub Category > Sub-Sub... > .... And to put all category,sub category,brand names in one model field.(In one database column). Isn't it easier to arrange them in different model fields and using foreign-key to each other and not pointing to self?? Which is more relatable?? -
Django: How to authenticate users for multiple app in Django?
I created a Login and signup app in Django Now I created another app for the profile page but I am unable to inherit user information that app. I used Django built-in Authentication and User models for that. Plz, Help. -
Django channels, AttributeError
I'm trying to learn how to send messages over a websocket using channels 2. I'm trying just to send a simple message when a client connects but I keep getting Attribute Errors: class CameraOnlineConsumer(JsonWebsocketConsumer): def connect(self): self.accept() return self.send({ "type": "websocket.accept", "send": {'a': "Hi"} }) raises: self.sendMessage(content.encode("utf8"), binary) AttributeError: 'dict' object has no attribute 'encode' WebSocket DISCONNECT /ws/camera_online/connect [127.0.0.1:36006] changing to: return self.send({ "type": "websocket.accept", "send": "Hi" }) for example, returns the same error. -
How to create Likes button on wagtail
Now, I am developing the website for studying Japanese and want to create Likes button on my website by wagtail. However it's so confusing me. Anyway, This is the core code. I coded them while I saw a couple of website about Like button in Django as my reference. However, This is for Django, is not completely same with wagtail, and while repeating finding out website and add codes, the code is awful disorder and I didn't know where I am, so, I really need your help. What I did Defining Article and Like on Blocks.py Inheriting that and modeling Articles and Like as a class (Folder:Articles) although I wrote urls.py and Views.py, how to write path is incorrect, perhaps. Following code is a model class about Like. #url.py from articles import views from articles.views import ( LikeButton, ) url(r'like/', views.LikeButton, name="like_page"), #url(r'^(?P[\w-]+)/like/$', LikeButton.as_view(), name='like_api'), -
Unable to connect to Amazon RDS Postgres Database from my Django Web Application
I am trying to deploy a website using elastic beanstalk and connect it up to a Postgres Database. When trying to makemigrations in django I am getting an error. I have been able to successfully set up a local Postgres database. I have been trying for a while with no luck. This is the Error Log (venv) C:\Users\dania\Development\Cliquefit>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "cliquefit.c8lfjtthzko9.ap-southeast-2.rds.amazonaws.com" (13.239.177.165) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\migrations\loader.py", β¦ -
django- onclick function do not works in for loop of django
I have Created a button which onclick creat a another button , The code is like that <li ><button type="button" class="btn btn-danger" onclick="showdel();">Delete Photo</button></li> and in div where id is del the other button created , code id below {% if images %} <div class="row gallery-filter mt-4"> {% for image in images %} <div class="col-lg-4 col-sm-6 mix crossfit workout"> <div class="gallery-item"> <img src="http://127.0.0.1:8000{{ image.cover.url }}" alt=""> <div class="gi-hover-warp"> <div class="gi-hover"> <a href="{{ image.cover.url }}" class="image-popup"><i class="fa fa-search-plus"></i></a> <h6>Time to Try a Bodyweight Workout <h6> </div> </div> </div> <div id="del"></div> </div> {% endfor %} {% else %} <center><h3 class="text-white ">No Images</h3></center> {% endif %} and code of java script function showdel(){ var div = document.getElementById('del'); div.innerHTML = '<center><button class="btn btn-danger">DELETE</button></center>'; } above photo is of the output. but I want that the button should create in below all the pictures -
How to solve CORS with Django and VueJs?
How to solve CORS with Django and VueJs? I have made some settings, but I can't solve it. Could anyone help? INSTALLED_APPS = [ .... 'rest_framework', 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True Axios axios.defaults.headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' } Access to XMLHttpRequest at 'https://api.novosite.com/api/token' from origin 'https://novosite.vip' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
Can't save changes to my settings.py file in django
Whenever I make any changes in settings.py file , and try to save it , I get an alert saying UNABLE TO SAVE:PERMISSION DENIED. First I thought it is because as I am not the owner of the folder . But after changing settings and gaining ownership I am still getting the same alertenter image description here -
Digg-style pagination limit page number showing in template
I am using django-el-pagination package and trying to implement digg-style pagination on my home template. I am displaying it with.. {% get_pages %} {{ pages.get_rendered }} and it is showing like this <1234567> which is fine but I want to add some css or class to change the way it look. It will be good if it only display 5 page number like <12345> instead of showing all page numbers. -
What will be the most efficient way to filter the objects in django
I am working on a basic ecommerce website.I have created a superuser page in which I would like to see all the orders as well as the order details like customer who ordered, their address etc. These are my models.py: class ShippingAddress(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True) address=models.CharField(max_length=200,null=False) email=models.EmailField(null=False) class Customer(models.Model): user=models.OneToOneField(MyUser,null=True,blank=True,on_delete=models.CASCADE) email=models.CharField(max_length=100) class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) complete=models.BooleanField(default=False,null=True,blank=False) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,) And this is my views.py: def superuser(request): user=User.objects.all() customer=Customer.objects.all() order=Order.objects.filter(complete=True) items=OrderItem.objects.all() shipping=ShippingAddress.objects.all() return render(request,"superuser.html",{'order':order,'items':items,'customer':customer,'shipping':shipping}) Currently in my template I am unable to iterate over the above context such that I can get all the orders and with the every order I can print their orderitems as well as shipping details as well as customer details. I tried in one way which was really in efficient that was to iterate over all orders then iterate over all orderitems and check if orderitem.order.id was equal to order.id . Please tell me what is the best method to pass the objects in context which are the most efficient for my need . And how to iterate over them in my template. Thanks -
Remove bullet points in RadioSelect Widget in django
I have a form that inherits from a model in Django that is rendered with a RadioSelect widget. I would like to remove the bullet points. Mi form is like this: class FormFromModel(forms.ModelForm): c1 = [(1, 'Answer 1'), (2, 'Ans2'), (3, 'Ans3'), (4, 'Ans4'), ] q1 = forms.IntegerField(label='Question.... ?', widget=forms.RadioSelect(choices=c1), initial=4) And in the HTML I'm doing: <table> <tr> <td><b> 1. {{Inputs.q1.label}}</b></td> </tr> <tr> <td> {{Inputs.q1}}</td> </tr> </table> I have something like: What currently have And I will like: What I want Any help is appreciated, Thanks -
The test outputs 2 errors I can't figure out where they came from
Guys I need help and then I'm racking my head everything seems to be correct but the code outputs an error I will be grateful for your help and if you share information and experience from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import WebDriverException import time MAX_WAIT = 10 class NewVisitorTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def wait_for_row_in_list_table(self, row_text): start_time = time.time() while True: try: table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertIn(row_text, [row.text for row in rows]) return except (AssertionError, WebDriverException) as e: if time.time() - start_time > MAX_WAIT: raise e time.sleep(0.5) #def test_can_start_a_list_and_retrieve_it_later(self): #self.browser.get(self.live_server_url) #header_text = self.browser.find_element_by_tag_name('h1').text #self.assertIn('To-Do', header_text) #inputbox = self.browser.find_element_by_id('id_new_item') #self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a to-do item') #inputbox.send_keys('buy knife') #inputbox.send_keys(Keys.ENTER) #self.wait_for_row_in_list_table('1: buy knife') #inputbox = self.browser.find_element_by_id('id_new_item') #inputbox.send_keys('Π‘Π΄Π΅Π»Π°ΡΡ ΠΌΡΡΠΊΡ ΠΈΠ· ΠΏΠ°Π²Π»ΠΈΠ½ΡΠΈΡ ΠΏΠ΅ΡΡΠ΅Π²') #inputbox.send_keys(Keys.ENTER) #self.wait_for_row_in_list_table('1: buy knife') #self.wait_for_row_in_list_table('2: Π‘Π΄Π΅Π»Π°ΡΡ ΠΌΡΡΠΊΡ ΠΈΠ· ΠΏΠ°Π²Π»ΠΈΠ½ΡΠΈΡ ΠΏΠ΅ΡΡΠ΅Π²') #table = self.browser.find_element_by_id('id_list_table') #rows = table.find_element_by_tag_name('tr') #self.assertIn('1: buy knife', [row.text for row in rows]) #self.assertIn('2: Π‘Π΄Π΅Π»Π°ΡΡ ΠΌΡΡΠΊΡ ΠΈΠ· ΠΏΠ°Π²Π»ΠΈΠ½ΡΠΈΡ ΠΏΠ΅ΡΡΠ΅Π²', [row.text for row in rows]) def test_can_start_a_list_for_one_user(self): self.wait_for_row_in_list_table('2: Π‘Π΄Π΅Π»Π°ΡΡ ΠΌΡΡΠΊΡ ΠΈΠ· ΠΏΠ΅ΡΡΠ΅Π²') self.wait_for_row_in_list_table('1: buy knife') def test_multiple_users_can_start_lists_at_different_urls(self): self.browser.get(self.live_server_url) inputbox = self.browser.find_element_by_id('id_new_item') inputbox.send_keys('buy knife') inputbox.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: buy knife') edith_list_url = self.browser.current_url self.assertRegex(edith_list_url, '/lists/.+') self.browser.quit() self.browser = webdriver.Firefox() self.browser.get(self.live_server_url) page_text β¦ -
What is the relationship with the variable user in Django with the User model?
I've noticed throughout my time studying Django that when I want to reference a users attributes I can do so by saying something like user.username etc. Obviously my assumption thus far has been that this variable "user" referencing the User model in Django but I haven't been able to find it anywhere officially. Can someone verify this to me so I can put this thought behind me? Thank you! -
Cannot assign "''": "IncomeExpense.username" must be a "User" instance
I hope all are fine and safe. I am working on this below code, trying the add data to the table by getting the values from the form. I have also marked where i am getting the error with "#" Please help me with this and let me know if you have any clarification required from this i have pasted views.py, models.py and createentry.html codes below.What might be the reason why i am getting this error and also explain me what can i change to get rid of this error. #views.py def create_entry_form(request): if request.method=='POST': entry_type=request.POST.get("expensetype") amount=request.POST.get("amount") details=request.POST.get("entrydetails") capture_date=time.strftime('%Y-%m-%d') entry_username=request.POST.get("entryusername") entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username) #getting_error_in_this_line entry.save() user_balance = UserBalance.objects.filter(username=username).values_list('balance', flat=True)[0] if entry_type=="income": total_balance = user_balance + amount else: total_balance=user_balance - amount update_balance=UserBalance.objects.get(username=username) update_balance.value=total_balance update_balance.save() return render(request, "homepage.html", {'name':username, 'balance':total_balance}) else: return redirect("www.google.com") #createentry.html <form action="{% url 'create_entry_form' %}" method="post"> {% csrf_token %} <div class="container register-form"> <div class="form"> <div class="note"> <p>Create Entry Form</p> </div> <div class="form-content"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <select name="expensetype" id="expensetype" class="form-control"> <option value="expensetype">Select Expense Type</option> <option value="income">income</option> <option value="expense">expense</option> </select> </div> <div class="form-group"> <input type="text" name="amount" id="amount" class="form-control" placeholder="Enter the Amount" value=""/> </div> </div> <div class="col-md-6"> <div class="form-group"> <input type="text" name="entrydetails" id="entrydetails" class="form-control" placeholder="Enter the β¦ -
How to use to make custom decorators in Django?
I am absolutely beginners in python, django framework. I don't know how to make custom decorators in django. I am trying to, if user's profile is 100% completed they can apply job, else they can shows the warning message "your profile is nit completed, please first of all complete your profile then apply this job" I have following this code models.py class profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True) random = models.CharField(max_length=50) image = models.ImageField(upload_to="profile_pics") def __str__(self): return f'{self.user.username} profile' def get_absolute_url(self): return reverse('jobseeker:profile_count') @property def percentage_complete(self): percent = { 'random': 50, 'image': 50} total = 0 if self.random: total += percent.get('random', 0) if self.image: total += percent.get('image', 0) return total decorators.py def complete_profile_required(view_func): def wrapper_func(request, *args, **Kwargs): if request.user.profile.percentage_complete == 100: print(request.user.profile.percentage_complete) return redirect('jobseeker:apply_job') else: return view_func(request, *args, **Kwargs) return wrapper_func views.py @login_required @jobseeker_required @complete_profile_required def apply_job(request): return render(request, 'apply_job.html') urls.py path('apply_job', views.apply_job, name='apply_job') it will returns the this error -
why onlick function in button tag not working properly
I have created a delete Photo button which works as if we click on it a another delete button appear in somewhere in code , the code is <button type="button" class="btn btn-danger" onclick="showdel()">Delete Photo</button> after that I created div element where that delete button should be created . <div id="del"></div> and function for this is . function showdel(){ var div = document.getElementById('del'); div.innerHTML = '<center><button class="btn btn-danger">DELETE</button></center>'; } But it is not working , please help -
TemplateDoesNotExist at /student/student_form/
When i try "http://127.0.0.1:8000/student/student_form/" it gives an error like TemplateDoesNotExist at /student/student_form/ Please help me to resolve these issues and thanks in advance This is my templates code in settings.py file TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is my views.py file def student_list(request): return render(request,"student_list.html") def student_form(request): return render(request, "student_form.html") def student_delete(request): return This is my url.py files urlpatterns = [ path('admin/', admin.site.urls), path('student/', include('student_reg.urls')) ] urlpatterns = [ path('student_form/', views.student_form), path('student_list/', views.student_list), ] This is my project structure βββ CRUD β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-35.pyc β β βββ settings.cpython-35.pyc β β βββ urls.cpython-35.pyc β β βββ wsgi.cpython-35.pyc β βββ settings.py β βββ urls.py β βββ wsgi.py βββ db.sqlite3 βββ manage.py βββ student_reg βββ admin.py βββ apps.py βββ __init__.py βββ migrations β βββ 0001_initial.py β βββ __init__.py β βββ __pycache__ β βββ 0001_initial.cpython-35.pyc β βββ __init__.cpython-35.pyc βββ models.py βββ __pycache__ β βββ admin.cpython-35.pyc β βββ __init__.cpython-35.pyc β βββ models.cpython-35.pyc β βββ urls.cpython-35.pyc β βββ views.cpython-35.pyc βββ templates β βββ base.html β βββ student_from.html β βββ student_list.html βββ tests.py βββ urls.py βββ views.py