Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JS files of django-smart-select not working. net::ERR_ABORTED 404
I want to use django-smart-select I have installed it via pip and used this command as mentioned in django-smart-select problems: sudo pip3 install git+https://github.com/digi604/django-smart-selects.git@js-unlinting-fixes I have added 'smart_selects' to settings.py and added these lines to URLs: url(r'^chaining/', include('smart_selects.urls')), also used this line in settings.py JQUERY_URL = True and as mentions again in problems added this lines to HTML: {% load staticfiles %} <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> but when I load the page it raises these errors. it leads to not working the second option in django smart select: GET https://example.com/static/smart-selects/admin/js/chainedfk.js net::ERR_ABORTED 404 GET https://example.com/static/smart-selects/admin/js/chainedm2m.js net::ERR_ABORTED 404 GET https://example.com/static/smart-selects/admin/js/bindfields.js net::ERR_ABORTED 404 models.py: class CustomerAddressProvince(LoggableModel): title = models.CharField(verbose_name='province', max_length=60) class CustomerAddressCity(LoggableModel): title = models.CharField(verbose_name='city', max_length=60) province = models.ForeignKey(CustomerAddressProvince, verbose_name='province', on_delete=models.CASCADE, related_name='cities') class CustomerAddress(LoggableModel): province = models.ForeignKey(CustomerAddressProvince, verbose_name='province', on_delete=models.SET_NULL, related_name='address_province', null=True, blank=True) city = ChainedForeignKey( CustomerAddressCity, verbose_name='city', chained_field="province", chained_model_field="province", show_all=False, auto_choose=True, sort=True, null=True, blank=True) -
bootstrap not working for djano send_mail
In my views.py I have the following code def cpio(request): mainDict9=['hemant','jay','yash','Hari'] args={'mainDict9':mainDict9,} msg_html =render_to_string('/home/user/infracom2/JournalContent/templates/JournalContent/test1.html', {'mainDict9':mainDict9,}) from_email = 'gorantl.chowdary@ak-enterprise.com' to_email = ['gorantla.chowdary@ak-enterprise.com'] subject="TESTING MAIL" send_mail('email title',subject,from_email,to_email,html_message=msg_html,) return render(request,'JournalContent/test1.html',args) In my test1.html I have my following code <!DOCTYPE html> <html> <table class="table table-bordered"> <thead> <tr> <th scope="col" class="table-secondary"><center>Modified Binaries/components</center></th> <th scope="col" class="table-secondary"><center>CRs</center></th> </tr> </thead> <tbody> {% for king in mainDict9 %} <tr> <td style="width: 10px;" class="table-active">{{ king }}</td> <td style="width: 10px;" class="table-active"></td> </tr> {% endfor %} </tbody> </table> </html> The problem is in my GUI the bootstrap code is working fine but when I send the content in mail bootstrap functions are not applying -
SSL: CERTIFICATE_VERIFY_FAILED trying to validate a reCAPTCHA with django
I'm getting a <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)> When I try to validate captchas in my django project. This is how i do it: recaptcha_response = request.POST.get('g-recaptcha-response') print(recaptcha_response) url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.CAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) # It fails here result = json.loads(response.read().decode()) print(result) The site has a valid certificate, and it works on local. In the log i'm getting this: Request Method: POST Request URL: http://prod.xxxx.com/evalua Which is weird because the site works in https. Its on kubernetes, could that be the problem? I really have no idea what the problem IS? I have the captcha keys correctly set up in de recaptcha admin console. And the certificate are not autosign. I use lets encrypt -
Using localhost for google chrome extension
I created a Google Chrome extension.I made a Django app to process the ajax request it sends.But when I use my localhost I get the following error: Access to XMLHttpRequest at 'http://127.0.0.1:8000/working' from origin 'chrome-extension://nmgmbpgmpjfoaefb' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have no idea how to make it work. -
Chaning Image Resolution Django
I am fetching images from website by using BeautifulSoup, but the resolution is too small, when I want to make image bigger by adding width attribute in src, it loses quality. Is it possible to enlarge image resolution which is downloaded from url? I've tried thumbnail sorl, but then images dissapeared views.py def home(request): source = requests.get('https://lol.gamepedia.com/Ultraliga/Season_3').text hours_games = ['17:30', '18:30', '19:30', '20:30', '17:30', '18:30', '19:30', '20:30'] soup = BeautifulSoup(source, 'lxml') first_team_images = [] first_team_images_res = [] team_image1 = None first_team_names = [] second_team_names = [] td1s = None td2s = None tables = soup.find_all('table', class_='wikitable matchlist') for table in tables: td1s = table.find_all('td', class_='matchlist-team1') td2s = table.find_all('td', class_='matchlist-team2') for td in td1s: span = td.find('span') first_team_names.append(span.text) span2 = span.find('span', class_='teamimage-left') team_image1 = span2.find('img')['src'] first_team_images.append(team_image1) for td in td2s: span = td.find('span') second_team_names.append(span.text) context = { 'all_teams':zip(first_team_names, second_team_names, hours_games, first_team_images) } return render(request, 'profilecontent/home.html', context) template {%extends 'profilecontent/base.html' %} {%block content%} <div class="container-home"> <div class="home-wrapper home-wrapper-first"> <p class='home-matches'>Przyszłe mecze <span class='home-week'>W3 D2</span></p> <div class="match-wrapper"> <ul class='team-schedule-list'> {% for data in all_teams %} <li class='item-team-schedule'><span class='team-describe first-team-name'>{{ data.0 }}</span> <img src="{{data.3}}" width='150' height='150' alt=""> <span class='hours-game'>{{ data.2 }}</span> <span class='team-describe2 second-team-name'>{{ data.1 }}</span></li> {% endfor %} </ul> </div> </div> <div class="home-wrapper … -
How to stop __init__ of a class based view executing twice in django?
I have shuffled the questions and corresponding options in the exam. Once student has wriiten the exam score will be displayed, and I want to show the student their answer sheet in the same way as they have seen while writing the exam with their answers and correct answers. So I decided to use random.seed(). Why init() is executing twice ? [12/Mar/2020 14:08:58] "GET /exam/4/ HTTP/1.1" 200 11103 [12/Mar/2020 14:41:15] "GET / HTTP/1.1" 200 5059 init seed = 13 student now writing the exam with seed = 13 [12/Mar/2020 14:41:24] "GET /exam/3/ HTTP/1.1" 200 13156 init seed = 57 saving seed = 57 [12/Mar/2020 14:42:04] "POST /exam/3/ HTTP/1.1" 200 59 views.py class ExamDetailView(LoginRequiredMixin, DetailView): model = Exam #context_object_name = 'exam' def __init__(self, *args, **kwargs): super(ExamDetailView, self).__init__(*args, **kwargs) self.seed = random.randint(1, 100) print("init seed = ", self.seed) def setup(self, *args, **kwargs): super().setup(*args, **kwargs) print(dir) def get_context_data(self, **kwargs): context = super(ExamDetailView, self).get_context_data(**kwargs) try: self.seed = ResultPerExam.objects.get(student_id = self.request.user.id, exam_id = self.kwargs[self.pk_url_kwarg]).seed #checking sudent has already written the exam or not print("seed read from ResultPerExam is ", self.seed) context["has_written"] = True random.seed(self.seed) print("student already writen exam with seed = ", self.seed) except ResultPerExam.DoesNotExist: context["has_written"] = False random.seed(self.seed) context["seed"] = self.seed print("student now writing … -
I can't display OpenCV processed image in Django Template (sent as parameter)
My app works like this: My client uploads an image. I crop that image using OpenCV and want to display the cropped image in the next view. I don't want to store on my server any of these images. The image I get is stored in crop variable. I tried something like this: crop_png = png.from_array(crop, mode="L") content = crop_png.getvalue().encode("base64") img = "data:image/png;base64," + content return render(request, 'finish_page.html', {"img": img}) And tried to display like this in my finish_page.html <img src="{{img}}"> I receive the following error: 'Image' object has no attribute 'getvalue' I also tried this encoded_string = base64.b64encode(crop) mime = "image/png" img = "data:%s;base64,%s" % (mime, encoded_string) But still didn't work. And I've also tried something like this: output = io.StringIO() encoded_string = base64.b64encode(crop) encoded_string.save(output, "PNG") output.close() -
Display frames generated from opencv Django React
I want to show a video generated from opencv, I am getting each frame from opencv and with the help of the django I send this to react. So what happens, I send a request from react to django api to get frame from opencv and I then show that on react, I am calling this api in a loop to get multiple frames in a second and show on react ( its so fast that it shows frame in a form of video). But I found that its a wrong way I have to use sockets to send so much request at a time. Can some show me how can I get the same functionality through websockets,I have a short time so I need a smaller and quicker solution I have googled a lot but did't find nothing. here's my current approach of sending multiples request: const interval = setInterval(() => { axios .get("http://127.0.0.1:8000/MyApp/get_logs/") .then(res => { set_show(res.data); }) .catch(err => { console.log(err); }); }, 500); return () => clearInterval(interval); The above function is called after every 0.5 seconds, I get a frame in base64 and show it in image, and it happens repeatedely that makes it in a … -
Html button not changing color when toggled to on/off
{{ value.stat }} < The above is my html code which iam using in django.can any one please tel me how to change the color of the switch when i'm toggling it to on/off. -
changed the database settings.py from sql to postgres in server (nginx)
Developing a Django web application having geojson data, using postgres(postgis extension) as a database, while uploading the changes to the server done in my settings.py and running the project on the server, i am getting an error like this File "/opt/rh/rh-python36/root/usr/lib64/python3.6/ctypes/__init__.py", line 361, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: /usr/lib64/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 my settings.py looks like this: import os if os.name == 'nt': import platform OSGEO4W = r"root\my_project\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'my_app', 'leaflet', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], … -
Query to save data from json request in Django
I'm trying to create a Calorie Info API which saves calorie intake for a user. If it is a new user, then add an entry for the user id and item id. If the user already exists, If the item is new, then just map the item id and the calorie count with that user. If the item id is already mapped with that user, then add the items calorie count with that item for that user. Url: /api/calorie-info/save/ Method: POST, Input: { "user_id": 1, "calorie_info": [{ "itemId": 10, "calorie_count": 100 }, { "itemId": 11, "calorie_count": 100 }] } Output: - Response Code: 201 My model: class CalorieInfo(models.Model): user_id = models.IntegerField(unique=True) itemId = models.IntegerField(unique=True) calorie_count = models.IntegerField() I tried: class Calorie(APIView): def post(self, request): user_id = request.GET["user_id"] item_id = request.GET["item_id"] calorie = request.GET["calorie"] try: check = CalorieInfo.objects.get(user_id=user_id) except CalorieInfo.DoesNotExist: entry = CalorieInfo(user_id=user_id, item_id=item_id, calorie=calorie) entry.save() res = {"status": "success"} return Response(res, status=status.HTTP_201_CREATED) How to make a post request in the above format? -
How to get value in variable from Django template in views.py?
I am working in django and want to pass the value in views.py my code is HTML Template {% for doctor in doctor_list %} {% if citysearch == doctor.city %} <h1>Name of doctor is </h1> <form class="form" method="POST"> {% csrf_token %} <input type="submit", class="btn view", name="{{doctor.contactNumber}}" value="View Profile"> </form> {% endif %} {% endfor %} Views.py if request.method == 'POST': selectdocnum = request.POST.get["doctor.contactNumber"] print(selectdocnum) return redirect('patientPannel') This is not returning the value of doctor.contactNumber, and error is method object is not subscriptable -
Extract data from queryset
Models.py class MasterItems(models.Model): owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='ShipperItems_owner') name = models.CharField(max_length=255, default="", null=True) length = models.FloatField(blank=True, null=True) breadth = models.FloatField(blank=True, null=True) height = models.FloatField(blank=True, null=True) weight = models.FloatField(blank=True, null=True) class SalesOrderItems(models.Model): item = models.ForeignKey(MasterItems, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) class SalesOrder(models.Model): owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='so_owner') client = models.ForeignKey(MasterClient, on_delete=models.CASCADE, related_name='so_client') items = models.ManyToManyField(SalesOrderItems, related_name='items_so', blank=True, null=True) From the frontend I am receiving pk of sales order for e.g [4,2] and I want to extract the Items associated with these SalesOrder What I tried: items = [] for i in sales_orders: so_items = SalesOrderItems.objects.filter(items_so=i) print("so_items ", so_items) items.append(so_items) But the output I get is this: items = [<QuerySet [<SalesOrderItems: SalesOrderItems object (4)>, <SalesOrderItems: SalesOrderItems object (5)>]>, <QuerySet [<SalesOrderItems: SalesOrderItems object (1)>]>] How can I get the items name ? -
OperationalError : "no such column" when using ForeignKey in Django
so I'm trying to make a user-specific page with Django. In my models.py file, I have this code: class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", null=True) name = models.CharField(max_length = 200) def __str__(self): return self.name But I keep getting this "no such column: main_todolist.user_id" error. I'm aware that when using ForeignKey, Django automatically creates a column named '..._id' as I do the makemigrations and migrate command. I've also tried deleting all the migrations and pycache files except 'init.py', but nothing works. I would very much appreciate your help. :) *The version of my Django is 3.0.4 -
Problem with loading static files on Django
I'm using Django 3.0.3 and Python 3.7.6. I followed Django documentation on https://docs.djangoproject.com/en/3.0/howto/static-files/ but I can't find out what's wrong. Directory: project_name -app_name -static -css -main.css -js ... -project_name ... -settings.py settings.py: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ] ... STATIC_URL = '/static/' When I try to use static files in my templates: {% load static %} <link rel="stylesheet" href="{% static "css/main.css" %}"> pycharm shows unresolved template reference '"css/main.css"' terminal shows "GET /static/css/animate.css HTTP/1.1" 404 1671 -
key values of dictionary is not showing in html by django
I just start learning Django and I came across this problem in which my key values "hello world" of a key "hello" is not showing in the HTML page, I hope you guys help me to understand this code homepage.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>this is html page</h1> {{ hello }} </body> </html> urls.py from django.urls import path import view urlpatterns = [ path('',view.homepage), ] view.py from django.http import HttpResponse from django.shortcuts import render def homepage(request): return render(request, "homepage.html", {'hello':'hello world'}) -
I want to generate PDF using Reportlab
Currently I am using Weasyprint to generate my PDFs and want to try using reportlab, How do I edit my current codes to use reportlab instead of weasyprint? Thank you! from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML import tempfile def generate_report(request, test_id): #somethings here html = render_to_string(f'{lang}.html', { 'some': some.where }) html = HTML(string=html) result = html.write_pdf() # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = f'attachment; filename={test.test_taker.name}.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response -
Django OAuth Toolkit - AttributeError: get_full_path
I'm trying to setup the token authentication but when I try to get a token, i get this error. Endpoint is '/o/token/'. When i POST a wrong client_id or a wrong grant_type, i receive the response i expect: { "error": "invalid_client" } or { "error": "unsupported_grant_type" } But when sending the actual data (grant_type, client_id, username, password) it crashes: Internal Server Error: /o/token/ Traceback (most recent call last): File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauth2_provider/views/base.py", line 260, in post url, headers, body, status = self.create_token_response(request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauth2_provider/views/mixins.py", line 124, in create_token_response return core.create_token_response(request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauth2_provider/oauth2_backends.py", line 145, in create_token_response headers, extra_credentials) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py", line 116, in wrapper return f(endpoint, uri, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/token.py", line 119, in create_token_response … -
django: ManyToMany: Upating and Insert Business rules
Note: New to django. Doing my with project with it. So I certainly lack many understand and the answer could be trivial. I have a ManyToMany relationship. I have trouble coming up with an analogy but on the "main" side we have a container which contains one or more items. In my case the items aren't "real" things but more like a "template" and templates are unique. This is the background. The business rules are that changes only happen and are initiated on the container side. So the form shows a container an it's items. A user can change one of the items. If an item in a container changes, the item instance (row in database) must not change, as said, it's a template used in many other containers. So the logic must be that if a user changes an item, a lookup is done if it already exists and if yes, instead of updating the current item, reuse the existing one. If it doesn't exist, create a new one and use that. But under no circumstance should the existing one be changed. How and where (at which level) can I achieve this? I would really like to keep this … -
Finding the reason for "Failed to load resource: the server responded with a status of 500"
I am facing an issue in my live website. The stack I am using is Django, Postgresql, Celery, Gunicorn and Nginx in a ubuntu server. And the server has 2vCpus, 4GB of Ram, 25 GB SSD and 4TB data transfer, ubuntu 18. The situation in details - I have a website where user can upload image and after that server starts a task in background using celery and returns the task id to client. From client side, an ajax request starts which sends request to the server every 5 sec to check on the task. When we were trying to stress test the site using about 40 client uploading about 10 images each total 400 images at the same time (uploading an image is in an ajax function) then some results were successful but after some time the remaining ones failed. The error that is given on the console is: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Then I checked my server log and the result of "journalctl -u gunicorn" of that time: Mar 11 09:42:42 ubuntu-** gunicorn[17308]: - - [11/Mar/2020:09:42:42 +0000] "POST /upload/ HTTP/1.0" 500 27 "https:***" "Mozilla/5.0 (X11; Linux x86_64) … -
How to solve this problem? list indices must be integers or slices, not str
I would like to thanks to those people who want to help me in this problem, since no one answer my question here https://stackoverflow.com/users/12951147/mary?tab=bounties even it have bounty, btw its not the same question I just don't know how to figure this problem, and I’m completely stuck with this error, I am selecting a marked(selection box) for every student and for every core values then sending all data back to the database. I hope guys you can help me with this. this is my html <form method="post" id="DogForm" action="/studentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="hidden" value="{{teacher}}" name="teacher"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in behaviorperlevel %} <td colspan="8"><input type="text" value="{{core.id}}" name="core">{{core.Grading_Behavior__Name}}</td> {% endfor %} </tr> <tr> {% for corevalues in behaviorperlevels %} <td colspan="4" style="font-size: 12px"><input type="text" value="{{corevalues.id}}" name="coredescription">{{corevalues.Grading_Behavior.GroupName}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student name</td> {% for corevalues in behaviorperlevels %} <td colspan="4" style="font-size: 12px"><input type="text" value="{{corevalues.id}}" name="period">Q {{corevalues.Grading_Period.id}}</td> {% endfor %} </tr> {% for student in Students %} <tr> <td colspan="2"><input type="text" value="{{student.id}}" name="student">{{student.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td colspan="4"> <select name="Marking"> {% for behaviors in behavior %} <option value="{{behaviors.id}}">{{behaviors.Marking}}</option> {% endfor %} </select> </td> <td colspan="4"> <select name="Marking"> {% for behaviors in behavior %} … -
The current path, accounts/signup/index.html, didn't match any of these
After filling the signup form, I want to redirect my page to the post_list page of my blog. But I am getting the error as stated above. Below are my different files. accounts is app for managing the accounts and blog_app is app for managing other blog related activities. Blog is the root app. In Blog: urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog_app.urls')), url(r'^accounts/',include('accounts.urls')), path('accounts/login/', views.LoginView.as_view(template_name='blog_app/login.html'),name='login'), path('accounts/logout/',views.LogoutView.as_view(template_name='blog_app/base.html'),name='logout'), ] In accounts: views.py: from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm def signup_view(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # log the user in return redirect('blog_app:post_list') else: form = UserCreationForm() return render(request,'accounts/signup.html',{'form':form}) urls.py: from django.conf.urls import url from .import views app_name = 'accounts' urlpatterns = [ url(r'^signup/$', views.signup_view, name = "signup"), ] signup.html: {% extends 'base.html' %} {% block content %} <h1>Signup</h1> <form class="site-form" action="/accounts/signup/" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Signup"> </form> {% endblock %} in blog_app: urls.py: from django.conf.urls import url from blog_app import views from django.urls import path app_name = 'blog_app' urlpatterns = [ url(r'^$', views.PostListView.as_view(),name='post_list'), url(r'^about/$', views.AboutView.as_view(),name='about'), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(),name='post_detail'), url(r'^post/new/$', views.CreatePostView.as_view(),name='new_post'), url(r'^post/(?P<pk>\d+)/edit/$', views.UpdatePostView.as_view(),name='edit_post'), url(r'^drafts/$', … -
Why Django think OR is complex?
I read some model operation from Django's document, and find this I'm curious that OR in WHERE is just basic concept, why Django think it's a complex query? -
cannot add panel to openstack django horizon
I tried to add panel openstack compute panel group but it's not working I do manually python package because toe is not working here is my mypanel tree enter image description here panel.py from django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.dashboards.project import dashboard class Testpanel(horizon.Panel): name = _("Testpanel") slug = "mypanel.testpanel" permissions = ('openstack.project.compute', 'openstack.roles.admin') policy_rules = ((("compute", "context_is_admin"), ("compute", "compute:get_all")),) dashboard.Project.register(Testpanel) _12221_project_mypanel_test_panel.py from django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.dashboards.project import dashboard class Testpanel(horizon.Panel): name = _("Testpanel") slug = "mypanel.testpanel" permissions = ('openstack.project.compute', 'openstack.roles.admin') policy_rules = ((("compute", "context_is_admin"), ("compute", "compute:get_all")),) dashboard.Project.register(Testpanel) I can't not see mypanel on compute panel group /project dashboard What am I miss?? I just want to see mypanel name on dashboard -
How to create CRUDL API is using python for Automation Test Framework for servicenow?
I am trying to create a new python CRUDL API for the automated testing framework of ServiceNow using the fastAPI library in python. am stuck for the process. please help me with this task anyone