Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ElephantSQL and Django not working together, atuhentication failed
I have bumped into the following problem and still don't know how to fix it. For the record I am using mac. I would like to connect my djnago app to an elephantsql database, so I have changed the database info. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'abc', 'USER':'abc', 'PASSWORD':'password', 'HOSTS':'tai.db.elephantsql.com', 'PORT': 5432 } } I see my database working fine in pgAdmin 4, so there is no issue with that, but when I run python manage.py migrate got the following error: django.db.utils.OperationalError: FATAL: password authentication failed for user "abc" Do you have any tips how to go forward? -
issue httpresponseredirect:unable to redirect to homepage
I’m keeping getting this redirect wrong either I got the code wrong or it keeps running in an infinite loop. urls.py first app urlpatterns = [ path("",views.pomo,name="pomo"), path("agenda/",views.agenda,name="agenda"), path("notes/",views.notes,name="notes"), ] urls.py main urlpatterns = [ path('admin/', admin.site.urls), path("", include('pomofocus.urls')), path ("login/", include('accounts.urls')) ] urls.py accounts(2nd app) urlpatterns = [ path("register/",views.register_request, name="register") ] views.py from django.contrib import messages def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): #save user user = form.save() #login user login(request,user) #send success message messages.success(request,"Congrats you are registered now") return redirect(“pomofocus:pomo") messages.error(request,"Unsuccesful registration.Try again.") form = NewUserForm() return render(request,"account/registration.html",context={"register_form":form}) -
How do i store stored data in a new form?
Currently im facing a issue where this my edit webpage have to get the data out of the db and appear in a form (this form looks exactly like the add new device form page). How my add device page look like Currently for my edit page : I am able to extract the information from 2 different tables in the db and print them out on the page in a table format. But how do make it the same as my add device page. Under each textfield for my add device page, im using eg. {{forms.hostname}}. If i remove this and key in the specific key for the data in my edit page, theres no textfield and the text wont get display -
Mocking SQLite database calls for DJango ORM pytest
Below is the code from one of my django view which uses django ORM to fetch data, however running the same from pytest gives error: FAILED tests/test_views.py::TestViews::test_trendchart_view - AttributeError: 'NoneType' object has no attribute 'metricname' metrics = Metrics.objects.all() metric = metrics.filter(metricid=metric_id).first() metric_name = metric.metricname Looking at the error it seems that metric is None. Any idea how can I mock this call to return some dummy object? Below is my test case for reference: @pytest.mark.django_db class TestViews: def test_trendchart_view(self): kwargs={'event_id':1, 'ar_id':1, 'tcid':1, 'activemenu_id':1, 'metric_id':1} path = reverse('trendchart', kwargs=kwargs) request = RequestFactory().get(path) response = treandchartsummary(request,None,**kwargs) assert response.status_code == 200 -
View detailed view of model item directly in django admin
Django shows list of model items in admin panel, but don't want to show the list but I directly want to show the detail view . How can i do this ? -
Automatic id not getting assigned (Django PostgreSQL)
I am using a PostgreSQL 12 backend with Django 2.2. For one particular model of a complex project (with several apps and dozens of models), a model is not assigning the auto-incremented ID anymore. The model itself is innocuous: class SavedAnalysis(models.Model): title = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) sq = models.ForeignKey(SearchQuery, on_delete=models.SET_NULL, null=True, default=None) json = models.TextField(blank=True, default='') class Meta: unique_together = ['title', 'user'] ordering = ['user', 'title'] When I do either SavedAnalysis.objects.create(...) or create an instance and call save() on it explicitly, the id is being set to None. The object is being created correctly, only the Django-assigned AutoField "id" does not seem to increment. This exact code was working fine for a long time, but I had to move the database to a different machine recently and only this particular model seems to be affected. I suspected sqlsequencereset to be the cause but that has not helped as well. Now I am resorting to a "hack": s = SavedAnalysis(title=title, user=user, sq=q, json=j) s.save() if s.id is None: SavedAnalysis.objects.filter( title=title, user=user).update(id=SavedAnalysis.objects.order_by('-id').values_list('id', flat=True)[1] + 1) Anyone seen this before? I'd prefer that the expected behavior works rather than using a hack. -
AuthCanceled at /oauth/complete/facebook/
Request Method: GET Request URL: http://www.example.com/oauth/complete/facebook/?granted_scopes=public_profile&denied_scopes&code=AQBoM1W9l8X1lnsYCaspOQVi1nxYG1Vh3IDkdXOw1dcW5tG6dNfjzbrQ0APZlpIquhjdeMLsQ6Wd_vktM_7pCv2GI-Uqsvya7iVm7jdnX2nbaMPkF2f7JgznpVZLh5oRXQv2AvG0Syu-GZ4skYp2ZVDNvuWdfEu-OnpN_d0GsY-P07BwwsCIlIwL6CrR0GCjNK3_wSC4c8BTWXS9fPeKd7rQOZB863x9wEwVQDjCx-LgxL41_rGJlIbk01pFWPCze5GZvsFJe8xAvbzjO9E1Jrq6KGf2pddF4-78q3xLz-IG3Ary31DoSHS2POmb-KrPvMQvK96ouft-vUBUFcoEe83P&state=nTPuVRtqNf8wSmU9SiFRYozizutSAoAd Django Version: 3.2.5 Python Version: 3.8.10 Installed Applications:[ 'admin_interface', 'colorfield', 'carparking.apps.CarparkingConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django' ] Installed 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', 'social_django.middleware.SocialAuthExceptionMiddleware' ] Traceback (most recent call last): File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/utils.py", line 248, in wrapper return func(*args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/backends/facebook.py", line 97, in auth_complete response = self.request(self.access_token_url(), params={ File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/backends/base.py", line 238, in request response.raise_for_status() File "/home/pratik/myproject/env/lib/python3.8/site-packages/requests/models.py", line 953, in raise_for_status raise HTTPError(http_error_msg, response=self) During handling of the above exception (400 Client Error: Bad Request for url: https://graph.facebook.com/v8.0/oauth/access_token?client_id=819143458788732&redirect_uri=http%3A%2F%2Fwww.carparking.site%2Foauth%2Fcomplete%2Ffacebook%2F&client_secret=4c2c5ed7bf2e5911aaa3bb7f44b73688&code=AQBoM1W9l8X1lnsYCaspOQVi1nxYG1Vh3IDkdXOw1dcW5tG6dNfjzbrQ0APZlpIquhjdeMLsQ6Wd_vktM_7pCv2GI-Uqsvya7iVm7jdnX2nbaMPkF2f7JgznpVZLh5oRXQv2AvG0Syu-GZ4skYp2ZVDNvuWdfEu-OnpN_d0GsY-P07BwwsCIlIwL6CrR0GCjNK3_wSC4c8BTWXS9fPeKd7rQOZB863x9wEwVQDjCx-LgxL41_rGJlIbk01pFWPCze5GZvsFJe8xAvbzjO9E1Jrq6KGf2pddF4-78q3xLz-IG3Ary31DoSHS2POmb-KrPvMQvK96ouft-vUBUFcoEe83P), another exception occurred: File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_django/utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_django/views.py", line 31, in complete return do_complete(request.backend, _do_login, user=request.user, File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/actions.py", line 45, in do_complete user = backend.complete(user=user, *args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/backends/base.py", line 40, in complete return self.auth_complete(*args, **kwargs) File "/home/pratik/myproject/env/lib/python3.8/site-packages/social_core/utils.py", line 251, in wrapper raise AuthCanceled(args[0], response=err.response) Exception Type: AuthCanceled at /oauth/complete/facebook/ Exception Value: Authentication process canceled I think this error because of it … -
Jupyter runtimeerror
How can I solve this error? seis_model = Model(vp=reshaped, origin=(0., 0., -1000.), spacing=(10., 10., 10.), shape=shape, nbl=30, space_order=4, bcs="damp") RuntimeError: Couldn't find libc's posix_memalign to allocate memory -
Django: Can't save image from template
If I try to save image from admin site, it works properly. But I'm trying to save image from template, and its not working. here is my code models.py: class About(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profilePicture = models.ImageField(upload_to='images/profile/', default = 'images/useravater.png') views.py: def editProfile(request): if request.method == 'POST': profilePicture = request.FILES['pp'] About.objects.filter(user=request.user).update(profilePicture=profilePicture) # more code... html: <form style="width: 100%;" action="/editProfile/" method="POST" enctype="multipart/form-data">{% csrf_token %} <input id="inputpp" type="file" accept="image/*" name="pp" title="Select Image"> <!-- more code --> </form> after running this code, if i try to print: print(About.objects.get(user=request.user).profilePicture.url) it shows: Not Found: /media/image_name.jpg can you please find my problem? how do I save image to /media/images/profile/? -
How can I exclude entries if the max of my JSON Field values is 0?
I have this kind of JSON Field called fieldA : `{'test': 0, '1': 0, 'number': 0} And I would like to exclude if the max of the values is 0. I thought to use that if A is my query using Django ORM : A.exclude(fieldA ? Then I don't know how can I do this ... Could you help me please ? Thank you ! -
How to get the data from views to template Django
From my model I am uploading a file , In my views I perform some operations on the file .I am using DetailView of CBV of Django , In which I get one object and perform some operations on it . Now I want the data (after performing the operations) in my template . I know how to show the file in my template because the file is in models . But the functions are not in models and I want to print those in my template. My models.py is : class FileUpload(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True , null=True) file = models.FileField(upload_to='files') def get_absolute_url(self): return reverse('home') my views.py is : class PostDetailView(DetailView): context_object_name = "object_list" template_name = "post_detail.html" def get_object(self, *args,**kwargs): request = self.request pk = self.kwargs.get('pk') instance = FileUpload.objects.get(id = pk) #I want to print this instance if instance is None: raise Http404("File Does not EXIST") else: pdfFileObj = open(instance.file.path, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) print('number of pages = ',pdfReader.numPages) pageObj = pdfReader.getPage(0) print(pageObj.extractText()) #I want to print this query = pageObj.extractText() for j in search(query, tld="co.in", num=10, stop=10, pause=2): print(j) #I want to print this pdfFileObj.close() return instance -
Cannot Edit Form in Javascript With Django
I'm trying to edit a form on this site with Django, and save the edits using Javascript (but not mandating a page refresh). When the user clicks 'edit' on the page, nothing happens. No console errors. I think the issue is in the Javascript function edit_post. I'm new to using Javascript with Django. Any help is appreciated. Relevant urls.py path('edit_post/<str:id>', views.edit_post, name="edit_post"), #before was pk not id path('edit_post/', views.edit_post), path("profile/<str:username>", views.profile, name="profile"), Javascript function edit_handeler(element) { id = element.getAttribute("data-id"); document.querySelector(`#post-edit-${id}`).style.display = "block"; document.querySelector(`#post-content-${id}`).style.display = "none"; // everything above this works and opens up the form for editing edit_btn = document.querySelector(`#edit-btn-${id}`); edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); }} function edit_post(id, post) { const body = document.querySelector(`#post-content-${id}`).value; fetch(`/edit_post/${id}`, { method: "POST", body: JSON.stringify({ body:body }) }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = post; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).value = post.trim(); }); } Relevant html <span id="post-content-{{i.id}}" class="post">{{i.text}}</span> <br> <textarea data-id="{{i.id}}" id="post-edit-{{i.id}}" style="display:none;" class="form-control textarea" row="3">{{i.text}}</textarea> <button class="btn-btn primary" data-id="{{i.id}}" id="edit-btn-{{i.id}}" onclick="edit_handeler(this)" >Edit</button> <br><br> views.py def edit_post(request, id): post = Post.objects.get(id=id) form = PostForm(instance=post) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return JsonResponse({}, status=201) else: … -
Add a second attribute/category column to Django administrator GUI
I'm learning Django right now and I made this class called Clowns. On the Django Admin page I made two test objects. I made four attributes(dunno what they're called lol) for clowns. They are title, description, identification, and hobbies. See below: title = models.CharField(max_length=20) description = models.TextField() identification = models.CharField(default='-', max_length=5) hobbies= models.TextField() To make the "CLOWN" column you see in the image I added this to the clown class: def __str__(self): return self.title I seem to only be able to do this with one attribute/category, in this case it's title. How do I make another column for another attribute, say id? -
relation "users_user_groups" does not exist LINE 1: ... "auth_group"."name" FROM "auth_group" INNER JOIN "users_use
I have created Custom User Model in Django as follows, When I got Admin and click on User and then a particular user it gives me error : relation "users_user_groups" does not exist LINE 1: ... "auth_group"."name" FROM "auth_group" INNER JOIN "users_use... Thanks for solving it in advance! from django.db import models #from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin import uuid class UserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Email Requierd!") if not username: raise ValueError("Username required!") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): userid = models.UUIDField( default=uuid.uuid4, editable=False, primary_key=True) username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # USERNAME_FIELD = 'email' # REQUIRED_FIELDS = ['username'] objects = UserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perm(self, app_label): return True class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=85) last_name = models.CharField(max_length=85) recovery_email = models.EmailField(blank=True) img = models.ImageField(default='aavtar.png', upload_to='media') def __str__(self): return … -
Does using a foreign key as a column in the django admin interface create a new database query for each row?
I have a model relationship that looks like the following: class Author(Model): first_name = CharField() class Book(Model): title = CharField() author = ForeignKey(Author) I want an admin interface like this: class BookAdmin(ModelAdmin): list_display = ('title', 'author_name') def author_name(self, obj): return obj.author.name Does this create a new query for each row, or is django smart about using a join here? What if the relation is 2 or more levels deep instead of just 1? Using python 3.8, django 3.1, and Postgres 12. -
Flutter and Django, notification I need some north
I'm starting a project, my Django app communicates and receives data from an API, it might send notifications to the users when it receive something, I also wanna build a mobile app that receive these notifications, can someone indicate me what content should I look for? Is what I need something like web socket connection? -
Send the value of a disabled select in a form with a hidden input
I have a Django form, one of the parts is populated like this: <select {% if 'ba1' in widget.name or 'bs1' in widget.name or 'pm2' in widget.name %} disabled {% endif %} id="{{ widget.attrs.id }}" name="{{ widget.name }}" {% if widget.attrs.disabled %}disabled{% endif %} {% if widget.required %}required{% endif %} class="form-control form-control-sm {% if widget.errors %} is-invalid{% else %} is-valid{% endif %}" aria-describedby="{{ widget.id }}-help"> {% for value, label in widget.attrs.choices %} {% if value in widget.value %} <option value="{{ value }}" selected>{{ label }}</option> {% else %} <option value="{{ value }}" data="{{widget.value}}">{{ label }}</option> {% endif %} {% endfor %} </select> As it is a disabled field for ba1, bs1 and pm2 cases, that information will not be sent in the POST request. So what I have done is, through a hidden input, send the selected value of the disabled select. Unfortunately the value is always 0 instead of the correct value. I'm doing something wrong. Somebody could help me?. For example if the selected value is 2, or 3 or 4, it doesn't matter, the hidden input says that the selected value is 0, which is not correct. Hidden input code (not working, always value = 0) {% … -
Can I build a basic website to access my resume but slowly customize it using python to learn and showcase my skills?
I"m not entirely certain what I'm trying to do is doable. I want a ready made website that I can make live fairly quick but later modify it with python code. I have basic python knowledge and used it, as well as SQL regularly as a BSA at a past job. I also have some experience with HTML, though I would need a heavy brush up to actually build a website. We focused more on flash at the time. (15 years ago or so). I want a basic templated website that I can make live with very little customization and gradually learn and modify it with python. If I'm understanding correctly, you can't run python in html, but you can run html in Django. I read about Django Templates but not entirely certain this will be ready to go without some serious python webbev knowledge. Is it possible to have Django framework run an html templated website? Or are Django templated websites easy to customize and make live? -
Why doesn't it return an HttpResponse even though render returns?
My html template and urlpatterns are checked OK, but it just doesn't response anything and saying like this The view search.views.search_list didn't return an HttpResponse object. It returned None instead. So what's wrong? If I return HttpResponse('hello world'), it still just tell me returning nothing? def search_list(request): #return render(request, '/', locals()) start_time = time.time() searched = True keywords = request.GET.get('q') print(keywords) message = '' if not keywords: return redirect('/') #words = keywords.split('') word = keywords post_list = Poem.objects.filter(Q(author_name__contains=word) | Q(model_name__contains=word) | Q(poem_name__contains=word) | Q(dynasty__contains=word) | Q(content__contains=word)) print(post_list) try: old_word = SearchHotspot.object.get(word=word) except: new_word = SearchHotspot() new_word.word = word new_word.count += 1 new_word.save() else: old_word.count += 1 old_word.save() limit = 10 paginator = Paginator(post_list, limit) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) end_time = time.time() load_time = end_time - start_time title = keywords + "- 众里寻他千百度" content = "蓦然回首,那人却在灯火阑珊处。" return render(request, 'search/result.html', locals()) -
AttributeError: object has no attribute 'decode' when using Selenium and Django
I have a Django crawler that stores all URLs in the database from a site and I'm trying to get Selenium to scrape the content of each of the URLs but I'm getting this error object has no attribute 'decode' here is the code snippet: tasks.py ... @shared_task def crawler(): options = webdriver.ChromeOptions() options.add_argument(" - incognito") browser = webdriver.Chrome( executable_path='./scraper/chromedriver', chrome_options=options ) urls = urlList.objects.all() for url in urls: if 'cl/terreno/venta' in urlparse(url).path: print(url) elif 'cl/sitio/venta' in urlparse(url).path: print(url) browser.get(url) timeout = 10 nombre = browser.find_element_by_xpath("//h1[@class='subtitulos fb_title']") descripcion = browser.find_element_by_xpath("//div[@class='descrip']/p[2]") aspectos_generales = browser.find_element_by_xpath("//div[@class='aspectos']") region = browser.find_element_by_xpath("//span[@class='_tag_style']") lugar = browser.find_element_by_xpath("//span[@class='_tag_style'][2]") precio = browser.find_element_by_xpath("//span[@class='val fb_value']") print("Nombre: {} \n" "Descripcion: {} \n" "Aspectos generales: {} \n" "Region: {} \n" "Lugar: {} \n" "Precio: {} \n" .format(nombre.text, descripcion.text, aspectos_generales.text, region.text, lugar.text, precio.text )) -
Permission error when writing files in django + ubuntu + apache
Following is the error message I receive when I save x.mp3 via django : Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'x.mp3' -
Django Show Distinct Values in List
I'm trying to create a table that shows only the unique values based on a specific column. The following code does not present any errors, but does not show the unique values as intended - any ideas where the mistake is? Why wouldn't this do the trick? return self.name.distinct('name') Example, I have 3 rows for Rob in my table because he has 3 addresses, but I am creating a list in my app that shows Rob, John, and Clayton and I only want Rob to show up once. views.py from django.http import HttpResponse from django.views.generic import TemplateView,ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Book class BookList(ListView): model = Book class BookCreate(CreateView): model = Book fields = ['name', 'address', 'birthdate', 'deathdate', 'description'] success_url = reverse_lazy('books_cbv:book_list') class BookUpdate(UpdateView): model = Book fields = ['name', 'address', 'birthdate', 'deathdate', 'description'] success_url = reverse_lazy('books_cbv:book_list') class BookDelete(DeleteView): model = Book success_url = reverse_lazy('books_cbv:book_list') models.py from django.db import models from django.urls import reverse class Book(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200, default='none') birthdate = models.CharField(max_length=200, default='none') deathdate = models.CharField(max_length=200, default='none') description = models.CharField(max_length=1000, default='none') def __str__(self): return self.name.distinct('name') def get_absolute_url(self): return reverse('books_cbv:book_edit', kwargs={'pk': self.pk}) book_list.html {% extends "base.html" %} {% … -
Creating a .java popup for Django Project
Please note - this is (to the best of my knowledge) not a duplicate question; there have been similar questions in the past but they involve applets and other features which no longer exist. I have a working .java file named SignaturePad.java that creates a pop-up screen (JFrame) allowing a user to draw their signature and save it as a png in my a folder in my src. I need it to be called by an HTML button in a Django based website. I have tried 2 things: Using <button onclick> to call JavaScript which calls the Java <button onclick = "MyFunction()">Sign!</button> <p id='demo'></p> <script> MyFunction(){ var opened = function(){ var Main = Java.type(SignaturePad); Main.runJava(); }; document.getElementById("demo").innerHTML = "Signature Recieved"; } </script> This was inspired by this video showing how to call Java from JS and this article showing how to use a HTML button to call a script. There seems to be an issue in even reaching MyFunction(), as I put a syntax error inside it and pressed the sign button, and no error was reported. Using Django/HTML POST Forms which calls Java <--! IN post_detail.html !--> <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Sign!</button> </form> # in views.py … -
Django Block Title Shows In Page Content
I was trying to add a title for one of my Django HTML templates. The title of the website changes but it also shows up as text on the page content. How do I fix this and why does this happen? base.html {% block head %} <head> <title>{% block title %}{% endblock %}</title> </head> {% endblock %} page.html {% extends "base.html" %} {% block head %} {% block title %}Some Title{% endblock %} {% endblock %} -
calling a class below of another class
I'm working on a django project with rest_framework and I have a problem with serializers. Here is my code: class CategorySerializer(serializers.ModelSerializer): featured_product = ProductSerializer(read_only=True) class Meta: model = Category fields = [ 'title', 'featured_product', ] class ProductSerializer(serializers.ModelSerializer): category = CategorySerializer(read_only=True) class Meta: model = Product fields = [ 'title', 'price', 'category', ] as you see, at ProductSerializer Im using CategorySerializer, and also at CategorySerializer I need to use ProductSerializer. if I run the code I get NameError: name 'ProductSerializer' is not defined. First try:I tried to write them in two different files and import them at top of both files but I got Circular Import errorSecond try:I defined an empty class with name of ProductSerializer class at the top of my code but it didn't worked.