Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I prevent a browser from downloading a file and automatically changing its name
I have a project which reads the database composition into a compose environment variable file .env. I use django to read it and generate it. Part of the code is as follows: content = "Stringtest" filename = ".env" response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename={0}'.format(filename) return response When I download the file using brower, the preceding comma is automatically removed and the file name is changed to env instead of the required .env How can I change the file name to remain the same? -
Plotly showing characters not rendering graph
I am new to Python, Django, and Plotly. I am trying to render a graph but I am unable to do so. The images below depict my problem. When my page loads it displays the graph as a set of characters of the sort. When I click F12 it shows the second image, just partially rendering the graph. I am not sure where I went wrong, I would really appreciate your help. from plotly.offline import plot import plotly.graph_objects as go def home(request): """Renders the home page.""" valuesX = []; valuesY = []; results = DTH.objects.filter(date__gte = '2019-12-01', date__lte = '2019-12-31'); for row in results: valuesX.append(row.date); valuesY.append(row.price); #fig = go.Figure([go.Scatter(x=[0,1,2,3], y=[0,1,2,3])]); fig = go.Figure([go.Scatter(x=valuesX, y=valuesY)]); plt_div = plot(fig, output_type='div', show_link=False, link_text="") return render_to_response('app/index.html', { 'plt_div': plt_div }) -
Need help setting value for "is_staff" and "is_superuser" for Django LDAP authenticated users
I new to both Django and LDAP. I am creating a Django application with LDAP authentication as the login system. I am able to connect to the LDAP server and authenticate using a preexisting account from LDAP, which then populate my MySQL database auth_user table to have data row like this: So my question is how can I set the value for "is_staff" and "is_superuser" to be 1? -- LDAP setting inside settings.py -- AUTH_LDAP_SERVER_URI = "ldap://ldap.m*****.com.my:389" AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("o=m*****net", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) # logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) -
Custom template Django allauth send confirmation email after signup
I have custom template view using allauth overriding the signup page. Signup is success and the user is added to database and email is not confirm, But no sending email for verification on my console. But when I am using the default view I received email confirmation on my console. Here's my custom view for signup form. from allauth.account.forms import SignupForm class RegisterView(TemplateView): def get(self, request): self.template = 'authentication/register.html' self.context = { 'form': SignupForm(), } return render(request, self.template, self.context) def post(self, request): form = SignupForm(request.POST) if form.is_valid(): form.save(request) messages.success(self.request, "Check your email for confirmation (check spam)!") return redirect('account_login') # this only redirect to my login page. else: self.template = 'authentication/register.html' self.context = { 'form': form } return render(request, self.template, self.context) Is there something I am missing like where I redirect after form is valid for sending email confirmation? -
Django Channels and server-side message sending
I have a desire to use Django-channels in order to display server-side logging to users, so that the user can see what processes are active, or what they are doing. Like, a server-side download in the background, with status updates in a web-page. I've followed the tutorial for making a chat server (at https://channels.readthedocs.io/en/latest/tutorial/index.html), with a few modifications to test out a few other things. Now I want to interface into that with a backend process, and I'm stumped. If I try to create a class that the backend loads, that inherits from WebsocketConsumer, then it fails to init because of a missing scope. As I understand it, the scope dictates what group the Websocket joins, so I'd want to make sure that data is accurate. I have also found django-eventstream, implementing Server-Sent-Events, which seems like it might be a good solution for my needs. Has anyone used that, and might clarify it is what I want? I don't want to go down that rabbit hole, only to have a badger chew my face off. -
Django, how to fetch username and password and pass to other application
I'm running a Django app which is integrated with login. Authenticated via done via LDAP. This web front post data to another application server via REST API. Currently, authentication is done via static to post data. But I would like to use the same credentials which users use to log in the front web, which is their user LDAP. How to pass the user and pass into python script to post the data on to another server? Thank you for your help. -
Unhandled Exception: WebSocketException: Connection towas not upgraded to websocket
I'm using pushpin in my django app, i followed this example https://github.com/fanout/django-grip#http-streaming when i connect with curl everithing it's fine but when i try to connect with flutter or angular i see the same error in the logs (angular, flutter) E/flutter (20159): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: WebSocketException: Connection to 'http://10.0.0.19:7999/camiones/camion/rt/#' was not upgraded to websocket The pushpin config file has the debug = true and auto_cross_origin=true -
django mathfilters in views.py
How to compute the final average of every students in views.py and post it in html template? for example I have two(2) students, I will get the average of every Grading Categories(Exam, Quizzes, Homework, Classwork) to get the final rating first is I need to compute it in views.py and post it in my html template, I don't know how to do it so please me guys -
How to handle an else function in a nested if statement
I have a nested if statement in a template:; {% if object in request.user.mymodel_set.all %} {% if object.pk == request.session.field_pk %} Selected {% else %} <form method="POST" action="myURL" class=""> {% csrf_token %} <input type="submit" value="Select"> </form> {% endif %} {% endif %} However the <input> does not render. It does when the parent {% if %} statement is removed. Am I missing something as to how the else statement is handled in this template? -
Join 2 tables in django
Select (..) FROM ActualTotalLoad INNER JOIN ResolutionCode ON ActualTotalLoad.resolutioncodeid = ResolutionCode.id I have a uri : /areaname/resolutioncodetext/date and I want to make the above query, so I can get the resolutioncodetext that is provided from this uri. I tried Actualtotalload.objects.select_related() but it excludes some columns . Ask for anything extra you might need models.py class Actualtotalload(models.Model): source = "entso-e" dataset ="ActualTotalLoad" actualtotalload_id = models.BigAutoField(db_column='Id', primary_key=True) # Field name made lowercase. entitycreatedat = models.DateTimeField(db_column='EntityCreatedAt') # Field name made lowercase. entitymodifiedat = models.DateTimeField(db_column='EntityModifiedAt') # Field name made lowercase. actiontaskid = models.BigIntegerField(db_column='ActionTaskID') # Field name made lowercase. status = models.CharField(db_column='Status', max_length=2, blank=True, null=True) # Field name made lowercase. year = models.IntegerField(db_column='Year') # Field name made lowercase. month = models.IntegerField(db_column='Month') # Field name made lowercase. day = models.IntegerField(db_column='Day') # Field name made lowercase. datetime = models.DateTimeField(db_column='DateTime') # Field name made lowercase. areaname = models.CharField(db_column='AreaName', max_length=200, blank=True, null=True) # Field name made lowercase. updatetime = models.DateTimeField(db_column='UpdateTime') # Field name made lowercase. totalloadvalue = models.DecimalField(db_column='TotalLoadValue', max_digits=24, decimal_places=2) # Field name made lowercase. areatypecodeid = models.ForeignKey(Allocatedeicdetail,db_column='AreaTypeCodeId', on_delete = models.CASCADE, blank=True, null=True) # Field name made lowercase. mapcodeid = models.ForeignKey(Mapcode,on_delete = models.CASCADE, db_column='MapCodeId', blank=True, null=True) # Field name made lowercase. areacodeid = models.ForeignKey(Areatypecode,related_name='areatypecode',on_delete = models.CASCADE, db_column='AreaCodeId') # Field … -
How to get correct queryset for Datatable
I have two Models, Profile and Payment. And i need to show at the front-end a Datatable with the fields "Username","Email" and "Total Spent". Username and Email can be fount at Profile model, so the queryset would be: def get_initial_queryset(self): return Profile.objects.all() However, the "Total Spent" information needs to be calculated as the Sum of all "payment_amount" fields found at Payment model for the same "profile_id", since a user can have two Payments (one with amount=5 and another one with amount=15, and i need to show total_spent=20). The problem is, since i'm using Datatables, i NEED this "total_spent" field to be in the queryset (using Annotate or another method). I've tried using Subquery and OuterRef, but i'm getting erros in the final SQL generated. return Profile.objects.all().annotate( money_spent=Subquery( Payment.objects.filter(user_id__in=OuterRef('id')).annotate( money_spent=Sum('amount') ), output_field=CharField() ) ) But this gives me SQL error: (1241, 'Operand should contain 1 column(s)') How can i get the correct queryset ? Django Version: 1.11 | Python Version: 3.6.8 -
FileNotFoundError is showing in django code when attempting to extract JSON data in a python file
I am trying to extract and input data into a JSON file from python code in the views.py file of a django webapp, but once I run the server, I get a FileNotFoundError for the prices.json and the accountInfo.json files, altoughh the directory is correct from where the file is. I tried doing "./filename" to indicate that it is in the current directory, but that has not worked either. from django.shortcuts import render from .forms import ListForm from django.http import HttpResponseRedirect import json robinUser = '' robinPass = '' capitalToInvest = 0 def MakeMoney(request): if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): robinUser = form.cleaned_data['robinUser'] robinPass = form.cleaned_data['robinPass'] capitalToInvest = form.cleaned_data['capitalToInvest'] return HttpResponseRedirect('/index.html/') else: form = ListForm() return render(request, 'home.html', {'form': form}) def getJSON(filePathAndName): with open(filePathAndName, 'r') as fp: return json.load(fp) def overwriteJSON(data): with open("./prices.json", 'w') as fp: json.dump(data, fp) def StartProgram(request): rawJSON = getJSON('templates/prices.json') rawJSON['capital'] = int(capitalToInvest) with open('templates/prices.json', 'w') as fp: json.dump(rawJSON, fp) rawJSON2 = getJSON('templates/accountInfo.json') rawJSON2['email'] = robinUser rawJSON2['pass'] = robinPass with open("templates/accountInfo.json", 'w') as fp: json.dump(rawJSON2, fp) return render(request, 'index.html') Here is the error message: [Errno 2] No such file or directory: 'templates\\prices.json' Any help on this issue would be greatly appreciated. Thank you in … -
How to customize django-pagedown?
I am using django-forms to render the preview. However, I cannot seem to incorporate MathJax scripts in it. The documentation seems to imply that I can customize the library by extending it like this: from pagedown.widgets import PagedownWidget class MyNewWidget(PagedownWidget): template_name = '/custom/template.html' class Media: css = { 'all': ('custom/stylesheets.css,) } js = ('custom/javascript.js',) but I don't know where to put the code and have it run. The only other idea is using this JavaScript function here but I don't know how to incorporate it either. Please help. -
My security settings are probably not execute, django production - docker
I am preparing django applications for production. docker-compose exec web python manage.py check --deploy Detects 8 warnings for me. System check identified some issues: WARNINGS: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W006) Your SECURE_CONTENT_TYPE_NOSNIFF setting is not set to True, so your pages will not be served with an 'X-Content-Type-Options: nosniff' header. You should consider enabling this header to prevent the browser from identifying content types incorrectly. ?: (security.W007) Your SECURE_BROWSER_XSS_FILTER setting is not set to True, so your pages will not be served with an 'X-XSS-Protection: 1; mode=block' header. You should consider enabling this header to activate the browser's XSS filtering and help prevent XSS attacks. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. ?: (security.W009) Your … -
Django + S3: files not synching to S3
I inherited a CMS system that was implemented using Django Suit. One of the forms is supposed to upload files to S3 but it's not happening (the files upload to the webserver - EC2, but not to S3). What I determined so far: The EC2 instance has full access to S3 (via a role) The user set up in Django's config file has full access to S3 There is a CloudFront configured to point to the bucket, and it works when files are accessed via a URL. The configuration is working there The previous developers used the following for handling the upload of files: DEFAULT_FILE_STORAGE = 'fallback_storage.storage.FallbackStorage' FALLBACK_STORAGES = ( 'django.core.files.storage.FileSystemStorage', 'main.custom_storages.MediaStorage' ) I looked into these 3 classes to see if I'm missing a configuration but everything looks good. I'm not familiar with this way of syncing files between a web server and S3, so I may be missing something very obvious. Is there like a cron jon that needs to run in the background? I found a blog post explaining how to use Django to upload files to S3 using FallbackStorage. That tutorial uses docker. In this case, docker is not used at all. I'm lost at this … -
Django REST framework reverse relationship object instance
Let's say that we have models like below class Movie(models.Model): """Stores a single movie entry.""" title = models.CharField(max_length=200, blank=False) class Watchlist(models.Model): """Stores a user watchlist.""" user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='watchlist', on_delete=models.CASCADE) movie = models.ForeignKey(Movie, related_name='watchlist', on_delete=models.CASCADE) added = models.BooleanField(default=False) Serializer class CustomUserSerializer(serializers.HyperlinkedModelSerializer): """Serializer for a custom user model with related user action.""" url = serializers.HyperlinkedIdentityField( view_name='customuser-detail', lookup_field='username') watchlist = serializers.HyperlinkedRelatedField( many=True, view_name='watchlist-detail', read_only=True) class Meta: model = CustomUser fields = ('url', 'username', 'watchlist') and the view: class CustomUserViewSet(viewsets.ReadOnlyModelViewSet): """ list: Return a list of all the existing users. retrieve: Return the given user with user's watchlist. """ queryset = CustomUser.objects.all() permissions = (IsAdminOrReadOnly) lookup_field = 'username' serializer_class = CustomUserSerializer That all will give us a user and hyperlinked filed to the particular watchlist. { "url": "http://127.0.0.1:8000/api/v1/users/John/", "username": "John", "favorites": [ "http://127.0.0.1:8000/api/v1/watchlist/2/", "http://127.0.0.1:8000/api/v1/watchlist/1/" ] }, but instead of that I would like to get a particular movie instance like that. { "url": "http://127.0.0.1:8000/api/v1/users/John/", "username": "John", "favorites": [ "http://127.0.0.1:8000/api/v1/movies/33/", "http://127.0.0.1:8000/api/v1/movies/12/" ] }, so my question is how can I achieve that? I tried with hyperlinkedrelatedfield but nothing seems to work as expected. -
JavaScript function needs to be reloaded for specific elements instead of the entire page in Django
I have the following form in Django and every time a user selects the Finalized option, two fields should become non-editable and when the user selects the Active option then those two fields should become editable again. However, it seems that this works only once the page is first loaded, then I need to select to another option and then reload the entire page to make the JS code to work. {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <body onload="makeReadOnly();"> <div id="form-group"> <form method="POST" action="." enctype="multipart/form-data"> {% csrf_token %} <div class="tweet-composer"> <label>Insert your task</label> {{ form.task|add_class:"card js-keeper-editor" }} </div> <label>Select your category</label> {{ form.category|add_class:"card" }} <label>Current points:</label> {{ form.points|add_class:"card" }} {% endif %} <button type="submit" class="btn btn-success">Send</button> </form> </div> </body> {% endblock content %} <script type="text/javascript"> {% block jquery %} function makeReadOnly(){ if (document.getElementById('id_status').value == 'Finalized'){ document.getElementById('id_task').readOnly=true; document.getElementById('id_category').readOnly=true; }else if (document.getElementById('id_status').value == 'Active'){ document.getElementById('id_task').readOnly=true; document.getElementById('id_category').readOnly=false; } {% endblock %} </script> How can I make the JS to load immediately after options are changed instead of changing one option and then reloading the entire page? -
How to simulate function in ModelViewSet's perform_create method in writing testcases using Django Rest framework
I am trying to write a TestCase for Django's using rest framework to test a Post Method. I have written a serializer and ModelViewset to achieve this. In my ModelViewSet I have a perform_create method, where I am calling a function. The return value from this function also needs to be saved in Serializer. So my question is how do I override this function so that I can correctly test my Post Method? ### My ViewSet class SampleView(ModelViewset): serializer_class = ... permission_classes = ... def get_queryset(self): query = ... return query def get_serializer_class(self): ... ... return serializer_class def perform_create(self, serializer): test_action = test_action() # Function call serializer.save(user=self.request.user, action=test_action) and my TestCase below ### My TestCase def test_sample_view_create(self): """Test a sample""" payload = { 'data': 'data', 'action': 'TRUE', 'user': self.user.id, } res = self.client.post( SAMPLE_URL, json.dumps(payload), content_type='application/json' ) sample = Sample.objects.get(id=res.data['id']) self.assertEqual(res.status_code, status.HTTP_201_CREATED) # Passes self.assertEqual(payload['data'], job.project.data) # Passes self.assertEqual(payload['user'], job.user.id) # Passes self.assertEqual(payload['action'], job.node.action) # This fails because action is assigned run time ## Note: action field is optional, thats why res.status passes So I need help on how I can either override test_action() method in my ModelViewSet or simulate the returned value from there. Also please help if there … -
Adding a vaiable to a static file path
I have this line in some javascript { url: "{% static 'volumes/123.nxs' %}" } the script does what it should, however I would like to replace the file name with a value from Django, {{ context.number }} I've tried simply doing the following but it does not work. Am I going in the right direction? { url: "{% static 'volumes/' + {{ context.number }} + '.nxs' %}" } Side question, the file is currently in the static folder, but moving forward in might be better to have them in another folder not under Django (for various reasons), how would I go about setting some kind of multimedia folder? -
Issue in showing current availability capacity of the membership plan in django
I want this functionality When admin try to add new membership of the user he will see current available capacity of the plan and if capacity is available subscribe the plan. class Membership(models.Model): membership = models.CharField(verbose_name=_('Membership Type'), choices=Plan_Interval, default='three_months', max_length=30) age_group = models.CharField(verbose_name=_("Age Group"), choices=Age_Group, default='6 years', max_length=30 ) session = models.CharField(verbose_name=_('Session'), choices=Per_Session, default='', max_length=30) capacity = models.IntegerField(verbose_name=_('Available')) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("created_at")) def __str__(self): return " age_group %s and session is %s" % (self.age_group, self.session) class Player(models.Model): membership_type = models.ForeignKey(Membership, on_delete=models.CASCADE) name = models.CharField(verbose_name=_("Name"), max_length=250) -
Django forms using html elements with different name from moels field
In my django project i have this model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,) u_fullname = models.CharField(max_length=200) u_email = models.EmailField() u_profile = models.CharField(max_length=1) u_job = models.CharField(max_length=100, null=True, blank=True, default='D') u_country = models.CharField(max_length=20, null=True, blank=True, default='Italy') u_regdata = models.DateTimeField(auto_now=True) stripe_id = models.CharField(max_length=100, null=True, blank=True) activation_code = models.CharField(max_length=10) u_picture = models.ImageField(upload_to='profile_images', blank=True) u_active = models.BooleanField(default=False) u_terms = models.BooleanField(default=False) def __unicode__(self): return self.u_profile and a forms.py like this one: from a_profile.models import UserProfile class ProfileModelForm(ModelForm): class Meta: model = UserProfile fields = ['u_fullname', 'u_job', 'u_country', 'u_email', 'u_terms', ] def clean(self): cleaned_data = super(ProfileModelForm, self).clean() u_fullname = cleaned_data.get('u_fullname') u_job = cleaned_data.get('u_job') u_country = cleaned_data.get('u_country') u_email = cleaned_data.get('u_email') u_terms = cleaned_data.get('u_terms') if not u_terms: raise forms.ValidationError("Please read and accept our Terms of Service") if not u_fullname and not u_job and not u_country and not u_terms: raise forms.ValidationError('You have to write something!') return cleaned_data well, now in html i have to use different names for element related to form fields: <form action="" method="POST"> {% csrf_token %} {{ form.errors }} <div class="row"> <div class="col-lg-12 no-pdd"> <div class="sn-field"> <input type="text" name="u_fullname_C" id="u_fullname_c" placeholder="Company Name"> <i class="la la-building"></i> </div> </div> <div class="col-lg-12 no-pdd"> <div class="sn-field"> <select name="u_country_c" id="u_country_c" value="{{ form.u_country }}"> <option selected="selected">Italy</option> <option>Spain</option> <option>USA</option> <option>France</option> </select> <i class="la … -
How do I delete my posts using django generic classes?
I want to delete my blog post but when I click confirm delete it says NoReverseMatch at /post/10/delete/ Reverse for 'post-by-author' with no arguments not found. 1 pattern(s) tried: ['post/detail/(?P<pk>[0-9]+)$'] Request Method: POST Request URL: http://127.0.0.1:8500/post/10/delete/ Django Version: 3.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'post-by-author' with no arguments not found. 1 pattern(s) tried: ['post/detail/(?P<pk>[0-9]+)$'] Exception Location: /Users/antonia/PycharmProjects/MySite/venv/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 Python Executable: /Users/antonia/PycharmProjects/MySite/venv/bin/python Python Version: 3.8.1 Python Path: ['/Users/antonia/PycharmProjects/MySite/mysite', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/antonia/PycharmProjects/MySite/venv/lib/python3.8/site-packages', '/Users/antonia/PycharmProjects/MySite/venv/lib/python3.8/site-packages/setuptools-40.8.0-py3.8.egg', '/Users/antonia/PycharmProjects/MySite/venv/lib/python3.8/site-packages/pip-19.0.3-py3.8.egg'] Server time: Tue, 14 Jan 2020 21:25:06 +0000 After I delete my post I want to go back to the user's post page? I also have named the file correctly for the Html form post_confirm_delete. I have tried to change what I have put inside reverse_lazy to (posts/post/blogs/blog/blog:index/blog:post-detail/ blog:post-by-author) nothing seems to work? class PostDelete(DeleteView): model = Post success_url = reverse_lazy('post-by-author') This the form {% extends "../base.html" %} {% block content %} <div class="container"> <h1>Delete Post</h1> <p>Are you sure you want to delete this post: {{ post }}?</p> <form action="" method="POST"> {% csrf_token %} <input type="submit" action="" value="Yes, delete." /> </form> </div> {% endblock %} my models class PostAuthor(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name='authors') bio = models.TextField(max_length=400, help_text="Enter your bio details … -
is there any way to count number of filtered columns in django with fk?
1.this is what I have tried and the user_name is foreign key I want to get the name and I am getting fk id. test.objects.filter(status='present').order_by('user_name').values('user_name').annotate(dcount=Count('status')) -
How to get background of each td in jquery?
I have a small problem with one function. Working on cinema app, currently on booking page. I have the table immitating the rows and numbers. One function changes the color of seat after click (actually double because it doesn;t work after one click, doesn't know why). Another function is responisble for gathering the data like row and number from highlited seats so it can be passed to views later on. The second function sees the elements in console.log, but when I want to get background colors, it returns undefined. Appreciate for any hints. {% extends "main_templates/main.html" %} {% load static %} {% block content %} <div class="container"> <table class="table table-bordered "> <tbody> {% for row in seats_range %} <tr> <th scope="row" class="bg-danger">{{row}}</th> {% for number in seats_range %} <td class="text-center" style="width:5%;" value="{{row}}" onclick="change_bg(this)"><a href="#"></a>{{forloop.counter}}</a></td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> <button type="submit" onclick="get_all_fields()">click me</button> <script> function change_bg(element){ var color_to_change = "rgb(121, 12, 131)" $(element).click(()=>{ console.log($(element).attr("value")) var color_now = $(element).css("background-color") if (color_now == color_to_change){ color_to_change = "rgb(255, 0, 0)" } $(element).css("background-color", color_to_change) }) } function get_all_fields(){ var array = [] var color_to_find = "rgb(255, 0, 0)" $(".table-bordered tbody td").each(()=>{ let element_color = $(this).css("background-color") if(element_color == color_to_find){ let … -
why my app_name show as plural by s by navigation into URL link? [login]
when I do submit this form why has been submitted by accounts/profile? I've no any file called accounts basically. my app_name calls account not accounts. so, How can I submit my form according to app_name that I using Image Error urls.py from . import views from django.conf.urls import url from django.contrib.auth.views import LoginView, logout app_name = 'account' urlpatterns = [ # /account/ url(r'^$', views.index, name="home"), # /account/login/ url(r'^login/$', LoginView.as_view(template_name='account/login.html'), name='login_page'), # /account/logout/ url(r'^logout/$', logout, {'template_name': 'account/logout.html'}, name='logout'), # /account/register/ url(r'^register/$', views.register, name='register'), # /account/profile/ url(r'^profile/$', views.view_profile, name='view_profile'), # /account/profile/edit/ url(r'^profile/edit/$', views.edit_profile, name='edit_profile'), # /account/profile/edit/ url(r'^change-password/$', views.change_password, name='change_password'), ] login.html {% extends 'base.html' %} {% block title %} Login {% endblock %} {% block body %} <div class="container"> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> </div> {% endblock %} I've no more files to explain that I think these files just show you what happens when logged in