Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide a user's access token that is sent from Django web application?
I am a beginner. I have been working on a Django web application that is integrated with the Webex API. After the OAuth grant flow, an access token is generated (expires after 14 days, so I stored it in a database) and the access token is used in the Webex space widget code to enable the video calling feature on the website. This webpage template along with the Webex space widget code is rendered with Django. But I'm worried about exposing the access token as anyone can see it with developer tools in the browser. Is there any way to hide this access token visible in the browser? This is the webpage code generated by Django <body> <div id="my-recents-widget" /> <script> var widgetEl = document.getElementById('my-recents-widget'); // Init a new widget webex.widget(widgetEl).recentsWidget({ accessToken: '3f9a677931960cf65b6f13d20d1f1cfbcb2b502321891038' }); </script> </body> When this webpage is rendered in the browser, the access token is visible to anyone using the browser's developer tools. I want to hide this token at the same time making the widget working. Is there any way I can achieve this? As I'm a beginner, a detailed explanation will be helpful. The widget code is available here -
What email API should i use to power an app where users can sign-up and then send emails?
I made a django app where users can sign-up, create an account (not email address) and then ideally send out emails through some specific flows I designed in the app. My question is "how should I power the email sending system?". I initially thought about using gmail api but i don't want users to download/upload their credentials et cetera et cetera so now I am looking at services like SendGrid for example. My ideal scenario is that I have a scalable way to onboard users and send emails. Potentially from different email addresses (one per user) but it's ok also from one same email address (and I can differentiate in the text/subject) Suggestions? -
Django post-form cannot validate when using Form with additional inputs
I have a form containing af MultipleChoiceField where the choices are created dynamic based on the given user class UpdateForm(forms.Form): def __init__(self,names,*args,**kwargs): super(UpdateForm,self).__init__(*args,**kwargs) self.fields["list_names"] = forms.MultipleChoiceField(choices = zip(names,names),widget=forms.CheckboxSelectMultiple,label="Pick some names") add_new = forms.BooleanField(initial=True, label="Add new names?",required=False) delete_missing = forms.BooleanField(label = "Delete names?",required=False) and it works fine as GET-request, the issues arrives with the post-request: My view is the following: def update(request): user = request.user list_names = MyModel.objects.filter(user=user).all().values_list("nick_name",flat=True).distinct() form = UpdateWishlistForm(names =list_names) if request.method == "POST": post_form = UpdateForm(request.POST) if post_form.is_valid(): list_names = post_form.cleaned_data["list_names"] add_new = post_form.cleaned_data["add_new"] delete_missing = post_form.cleaned_data["delete_missing"] messages.success(request, "Success") context = { "form":form, } redirect("home") else: #invalid post_form messages.error(request, "Error") context = { "form":form, } return render(request, "discounttracker/update.html") else: #Get request context = { "form":form, } return render(request, "myapp/update.html",context=context) The post_form = UpdateForm(request.POST) does not validate and the post_form.errors is empty. It does contain data though (before calling post_form.is_valid()) print(post_form) # UpdateForm: <UpdateForm bound=False, valid=Unknown, fields=(add_new;delete_missing;list_names)> print(request.POST.dict()) #<QueryDict: {'csrfmiddlewaretoken': ['...'], 'add_new': ['on'], 'list_names': ['test_name_1']}> -
Django Auto Count Field and User - Django
I am using Django to build a website and now need custom counting for each user. I need a separate count for data submitted by a user for each user separately. I have code that works but I have been trying for a long time to integrate user separation into it but I can't. I'm using a foreign key to separate user's data and I need a separate count for each user so all user's first data submitted starts with 1 and counts up from there. I also think it is easiest to keep it all in my models because that is where I have had the best luck but I could be wrong. Thanks in Advance! models: class Sheet_Building(models.Model): user = models.ForeignKey(User, default=True, related_name="Building", on_delete=models.PROTECT) user_count = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True, verbose_name='Inspection Date') time = models.TimeField(blank=True, null=True, verbose_name='Inspection Time') class Meta: ordering = ['-pk'] def __str__(self): return self.timeor 'None' def get_absolute_url(self): return reverse('list_building') def save(self, *args, **kwargs): self.user_count = Sheet_Building.objects.count() + 1 super(Sheet_Building, self).save() -
Django CookieCutter: django.db.utils.OperationalError: fe_sendauth: no password supplied
How to fix the fe_sendauth: no password supplied erorr? There's this open-source framework for Django that is production-ready (https://github.com/pydanny/cookiecutter-django) I don't exactly know the cause of the error, but I do have some ideas, and I'm going to list out all the possible things that could have led to that error. I've followed all steps from this doc (https://cookiecutter-django.readthedocs.io/en/latest/developing-locally.html) Here are some of my answers to when I initialised the cookiecutter: version [0.1.0]: 0.1.0 timezone [UTC]: GMT use_whitenoise [n]: n use_celery [n]: n use_mailhog [n]: y use_sentry [n]: y use_pycharm [n]: n windows [n]: y use_docker [n]: n use_heroku [n]: n use_compressor [n]: y Select postgresql_version: 1 - 13.2 2 - 12.6 3 - 11.11 4 - 10.16 Choose from 1, 2, 3, 4, 5 [1]: 1 Select js_task_runner: 1 - None 2 - Gulp Choose from 1, 2 [1]: 1 Select cloud_provider: 1 - AWS 2 - GCP 3 - None Choose from 1, 2, 3 [1]: 1 custom_bootstrap_compilation [n]: n Select open_source_license: 1 - MIT 2 - BSD 3 - GPLv3 4 - Apache Software License 2.0 5 - Not open source Choose from 1, 2, 3, 4, 5 [1]: 5 keep_local_envs_in_vcs [y]: y debug[n]: n And then … -
Django forms don't are saving any information
So I have been trying do build a manager of activities with django and I'm still on the scratch. I was trying to test if the code can simply show if a acitivity is done or not, but it don't change anything. Everything looks good to me and I don't know if the error is in the form, in the view that saves the form or in everything else. I already tried to change the widget and fields of form and haven't been succeed in it. models.py: from django.db import models from django.contrib.auth.models import User class Activity(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) is_complete = models.BooleanField() def __str__(self): return self.title forms.py: from .models import Activity class ActivityUpdateForm(ModelForm): class Meta: model = Activity fields = ['is_complete'] views.py: from .models import Activity from .forms import ActivityUpdateForm def home(request): acts = Activity.objects.all() if request.method == 'POST': form = ActivityUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('home') else: form = ActivityUpdateForm() context = { 'acts': acts, 'form': form, } return render(request, 'diary/home.html', context) template: {% for act in acts %} <form method="POST"> {% csrf_token %} <p>{{ act.title }}</p> <p>Is complete: {{ act.is_complete }}</p> {{ form }} <p>{{ act.author }}</p> <button type="submit">Submit</button> </form> {% endfor … -
Picking up broker_api from Django settings
I have a Django / Celery / Flower setup routing messages to RabbitMQ on windows. All works well except that I can't find a way to pick up the flower broker_api from the Django settings file. CELERY_BROKER_URL is picked up and the tasks can be viewed by Flower, but the Broker tab is blank. If I pass broker_api on the celery -A myapp flower commandline then I can view the Broker tab. e.g. The following works and the broker tab is populated celery -A myapp flower --broker_api=http://myuser:mypwd@localhost:15672/api/ However if I add the broker api into settings.py along with the CELERY_BROKER_URL, instead of passing on the command line, then this no longer works. e.g. CELERY_BROKER_API_URL = 'http://myuser:mypwd@localhost:15672/api/' I have tried different setting names including BROKER_API, BROKER_API_URL, CELERY_BROKER_API, CELERY_BROKER_API_URL and even FLOWER_BROKER_API and FLOWER_BROKER_API_URL. I have also tried adding a flowerconfig.py file with broker_api configured as per the Flower manual, but this doesn't seem to be picked up. Any ideas? -
travis selenium does't work - django - stripe - javascript redirection
I have a selenium test that work on my local machine. Creating test database for alias 'default'... System check identified no issues (0 silenced). ............. ---------------------------------------------------------------------- Ran 13 tests in 32.510s OK Destroying test database for alias 'default'... I use selenium to test stripe checkout. When I click() on button I get redirection to stripe checkout. It work with the javascript from stripe documentation: <script type="text/javascript"> // Create an instance of the Stripe object with your publishable API key var stripe = Stripe("{{ public_api_key }}"); var checkoutButton = document.getElementById("checkout-button"); const headers = new Headers({ 'X-CSRFToken': "{{ csrf_token }}" }) checkoutButton.addEventListener("click", function () { fetch("{% url "sale:detail" ordered.pk %}", { method: "POST", headers, }) .then(function (response) { response_json = response.json(); return response_json; }) .then(function (session) { return stripe.redirectToCheckout({sessionId: session.id}); }) .then(function (result) { // If redirectToCheckout fails due to a browser or network // error, you should display the localized error message to your // customer using error.message. if (result.error) { alert(result.error.message); } }) .catch(function (error) { console.error("Error:", error); }); }); </script> however when i do the same test on travis-ci I get this error: selenium.common.exceptions.TimeoutException due to the: WebDriverWait( selenium, timeout ).until( EC.url_changes(current_url) ) so, the url never change when … -
Ability to have users add/edit/remove form fields dynamically?
I am working on a project that requires a base form + template for ever user, based off of a simple model as such... class FloorPlan(models.Model): user = models.ForeignKey(account) stories = models.IntegerField() bathrooms = models.IntegerField() sqft = models.IntegerField() I know that JS will be needed to make this dynamic. So every user will have a base form and view, which displays just those 3 fields. Now I also want this form to be customizable in a sense to let the user add any extra fields, or also remove fields that are not used. Maybe they add backyard info, pool info, etc. I came across this app, https://github.com/askvortsov1/dynamic-django-forms but doesn't seem to fit what I need. I was thinking of adding an extra field called extra_field=models.ForeignKey(ExtraField) in the FloorPlan model, and make it a m2m, and in the ExtraField model just store the new fields the user wants to create. But design wise, dont think this would be best to let every user flood the DB? I've been looking around to find maybe a JS library too. Really just looking for some advice if anyone has created something similar, just looking for some pointers in the right direction. TY in advance! -
How to ran a function some time after the user enterd the url? Django
I have a page that 10 seconds after the user enterd a change to the database is made, how do i do that? I need to add this idea to both a class based view and a regular view. -
DRF nested through model serialization filtering
Each of my models is inherited from the base model, which contains the publishing_status field that helps me control whether or not the object is included in the returned data. class BaseModel(models.Model): class PublishingStatus(models.TextChoices): ACCEPTED = 'accepted', 'Accepted' REJECTED = 'rejected', 'Rejected' publishing_status = models.CharField( max_length=9, choices=PublishingStatus.choices, default=PublishingStatus.DRAFT, help_text="Publishing status represents the state of the object. By default it is 'draft'" ) class Meta: abstract = True Here are two models Word and Homonym they both inherit from BaseModel: class Word(BaseModel): definition = models.CharField(max_length=255) homonyms = models.ManyToManyField('self', through='Homonym', through_fields=('homonym', 'word')) class Homonym(BaseModel): homonym = models.ForeignKey(Word, on_delete=models.CASCADE) word = models.ForeignKey(Word, on_delete=models.CASCADE) Homonyms are basically words too, so I have self-reference here, but through the model Homonym so that I could control these relationships to be public or not for my website. Then follow the serializers and probably the solution should be passed here: class HomonymSerializer(serializers.ModelSerializer): class Meta: model = Homonym fields = '__all__' class WordSerializer(serializers.ModelSerializer): homonyms = HomonymSerializer(many=True) class Meta: model = Word fields = '__all__' Question: Currently, all homonyms are displayed, regardless of whether they are accepted or not. How can I restrict the nested serializer to include only homonyms with the publishing_status="accepted"? Here is my view: class WordRetrieveView(RetrieveAPIView): serializer_class … -
Programmatically trigger password reset in Django 3.2
The method detailed here no longer works. Importing django.contrib.auth.forms.PasswordResetForm results in the custom user class not being available (django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'accounts.CustomUser' that has not been installed). How do I send these emails programmatically? To avoid the X-Y Problem: I don't want user registration. I want admins to be able to create users by supplying an email address, at which point the user receives a password reset email. Upon resetting (more accurately, creating) a password, the user can log in and set a display name and other attributes. -
Django Elastic serach deleting some documents when pointing multiple documents to the same index
I have my django application where i am using django_elasticsearch_dsl to index document to later do elastic search with them. I have two similar models in database so i want the documents to be pointing to the same index in elastic search so later i can do a search with both of them like they are the same. Righ now my setup is like this @registry.register_document class HelpCenterDocument(Document): title = TextField() url = ESTextField('get_absolute_url') site_id = ESIntegerField('site_id') class Index: name = 'help-center-index' class Django: model = HelpCenterPage fields = ['title', 'content'] @registry.register_document class PageDocument(Document): title = TextField() url = TextField('get_public_url') class Index: name = 'global-search-page-index' using = 'global_search' class Django: model = Page When i do manage.py search_index --rebuild it will say that it created Indexing 90 'HelpCenterPage' objects Indexing 213 'Page' objects So with this my index should have 303 documents, this is not the case when i look at the count it shows i have "docs": { "count": 239, "deleted": 64 }, If i comment one of the @registry.register_document the count will be ok, but if i let both of them uncommented it will index only some of them These are the index stats { "_shards": { "total": … -
How to get all values from a Model instance on django
I'm using django signals with post_save and receiving an instance: @receiver(post_save, sender=ServiceOrder) def service_order_post_save(sender, instance, created, **kwargs): if created: print(instance) I just want to get all values from this instance without doing field per field (is a big Model). I tried: instance.objects.values() instance.values() list(instance) as expected all trys failed. -
How can I setup multiple Django Apps using Supervisor (including Gunicorn and Nginx)? bind() to [::]:8090 failed (98: Address already in use)
I already deployed a Django/Wagtail App using Supervisor, Gunicorn and Nginx (on Debian Buster), so I can reach it with http://xx.xxx.xxx.xxx:8090. /etc/nginx/sites-available/cms server { server_name xx.xxx.xxx.xxx; listen 8090; listen [::]:8090 ipv6only=on; error_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log; access_log /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/www.mysite.com/www/my-site/cms/admin_panel; } location /media/ { root /home/www.mysite.com/www/my-site/cms/admin_panel; } location / { include proxy_params; proxy_pass http://unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock; } } /etc/supervisor/conf.d/guni-mysite-admin.conf [program:guni-mysite-admin] command=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/bin/gunicorn admin_panel.wsgi:application --config /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py user=www.mysite.com autostart=true autorestart=true /etc/supervisor/conf.d/nginx-mysite-admin.conf [program:nginx-mysite-admin] command=/usr/sbin/nginx -g "daemon off;" autostart=true autorestart=true stderr_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-error.log stdout_logfile=/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/nginx-access.log stderr_logfile_maxbytes=2MB stdout_logfile_maxbytes=2MB /home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/etc/gunicorn/conf.py workers = 3 keepalive = 5 user = 'www.mysite.com' proc_name = 'admin_panel' loglevel = 'error' errorlog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-error.log' accesslog = '/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/var/log/gunicorn-access.log' bind = 'unix:/home/www.mysite.com/.local/share/virtualenvs/cms-WqsZ9qOt/run/gunicorn.sock' raw_env = ['DJANGO_SETTINGS_MODULE=admin_panel.settings.production'] pythonpath = '/home/www.mysite.com/www/mysite/cms/admin_panel' Now I added 2 more Django Apps the same way. Unfortunately Supervisor can´t bring them up. Sometimes 1 out of 3 runs, but most of the time none of them work. In case it works it creates 3 processes (idk if that´s how it is supposed to be). $ sudo lsof -i:8090 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 3631 root 16u IPv4 961301189 0t0 TCP *:8090 (LISTEN) nginx 3631 root 17u IPv6 961301190 0t0 TCP *:8090 (LISTEN) nginx 3632 … -
Getting error when trying run test "RuntimeError" Database access not allowed
I am facing below error ERROR: Database access does not allow def send_orders(): for order in Order.objects.all(): order.send() order.sent = True #factories.py class OrderFactory(....): amount = 100 sent = False #test_order.py def test_send_orders(order): send_orders() assert order.sent -
Django get current model id after model form save & redirect it with this pk to set as fk to another models fk in model form
Working on Django 3.2 & unable to save forms with reference to each other. Like Project>Photos>Assignments>Students every form is a model form & has a relationship with each other. I have one Project Model & Another is Photos, want to get id of project after save & redirect user next model form "Photos" with project id reference where project_id is FK in Photos Model & should be assigned automatically, Can someone please help on this. here is what I have tried. I'm looking for url somethig like this: URL for add project: http://example.com/projects/add-project URL for upload photos project: http://example.com/projects/1/upload-photos #urls.py path('add-project', views.submit_project, name='submit_project'), path('<int:project_id>/upload-photo/', views.upload_media, name='upload_media'), #model.py code class Project(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True, related_name='project_owner') title = models.CharField(max_length=200) #Photo Model class ProjectMedia(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) photo1 = models.ImageField(upload_to='projects/media/', null=True, blank=True) #Views.py def submit_project(request): if (request.user.is_authenticated): if request.method == 'POST': form = SubmitProjectForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] project = Project(title=title) project = form.save(commit=False) project.owner_id = request.user.id project.save() messages.success( request, 'Thank you! Your project has been submitted.') else: form = SubmitProjectForm() context = { 'form': form, } return render(request, 'add-project.html', context) #Photo submit view def upload_media(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = … -
Display Image in HTML from SSH with django
I'm trying to display a randomly fetched image via ssh-connection on an HTML page with Django. Currently, I save a temporary image and then display it in the HTML, but this doesn't seem to be necessary or right. views.py: def image_view(request): rgb_img = IMGLIB.get_random_img() # fetches the img with paramiko and returns numpy.array img = Image.fromarray(rgb_img, 'RGB') img.save(os.path.join(BASE_DIR, 'static/img/temp.png')) context = {} return render(request, 'app1/app1.html', context) IMGLIB.get_random_img() is a custom made python library for our postgis database and uses paramiko for ssh to fetch images: [...] with sftp.open(tif_path) as f: f.prefetch() s = f.read() with MemoryFile(s) as mem: file = mem.open() rgb_img = get_rgb_img(file) return rgb_img Since the original file is actually not .png or .jpg, but a .tif file its being convertet to "plain" rgb in get_rgb_img() Question: How can I efficiently display the RGB with my function-based view on HTML without storing it as a temporary file in Django? -
Can I use google social token to send email through gmail? Django app
I have a django app where I implementeed a method to sign-up through gmail authentication. Now I would like to allow users to send emails using my app through their gmail account. If a user signs-up with Gmail I have a social token from him, is that enough to allow them to send emails through gmail or do I need to go through the manual work of downloading credential.json for each users? -
How to style ModelForm Choicefield in Django?
I'm trying to style the ChoiceField options for the Medicines in a prescription ModelForm to be in this format: <select> <option value="">Select a Medicine</option> <optgroup label="Favorite Medicines"> <option value="First">Brufen - Abbott - 600 Mg - Tablets</option> </optgroup> <optgroup label="Other"> <option value="First">Brufen - Abbott - 400 Mg - Tablets</option> </optgroup> </select> Where I can get the values form my Medicine model, and check whether it is exits in the user's medicine's favorite list, if yes the medicine should exist in the 'favorite Medicines' group, otherwise it should show in 'Other' group. This is My forms.py: class PatientPrescriptionForm (ModelForm): patient = forms.CharField( label='', widget=forms.TextInput(attrs={'class': "text-field w-input", 'maxlength': "256", 'name': "prescPatient", 'data-name': "prescPatient", 'placeholder': "Add a Patient", 'id': "prescPatient"})) category = forms.ChoiceField( label='', choices=Medicine.CATEGORY, widget=forms.Select(attrs={'id': "PrescMedCat", 'name': "PrescMedCat", 'required': "", 'data-name': "PrescMedCat", 'class': "select-field w-select"})) dose = forms.CharField( label='', widget=forms.TextInput(attrs={'class': "text-field small w-input", 'maxlength': "256", 'name': "PrescDose", 'data-name': "PrescDose", 'placeholder': "Dose", 'id': "PrescDose", 'required': ""})) dose_unit = forms.CharField( label='', widget=forms.TextInput(attrs={'class': "text-field small w-input", 'maxlength': "256", 'name': "PrescDoseUnit", 'data-name': "PrescDoseUnit", 'placeholder': "Dose Unit", 'id': "PrescDoseUnit", 'required': ""})) EN_name = forms.ChoiceField( label='', widget=forms.Select(attrs={'id': "prescMedName", 'name': "prescMedName", 'required': "", 'data-name': "prescMedName", 'class': "select-field w-select"})) EN_route = forms.ChoiceField( label='', widget=forms.Select(attrs={'id': "prescRoute", 'name': "prescRoute", 'data-name': "prescRoute", 'class': "select-field-2 … -
Deploying Django application To AWS ElasticBeanstalk
I am trying to deploy a django application to AWS ElasticBeanstalk. I am working on a Linux machine. It all goes well but when deployment is done I get "502 Gateway Error". From a deep search I found that people with the similar problem created Procfile to the root directory of the project and added the following to that: "web: gunicorn--bind :8000 --workers 3 --threads 2 applicationName.wsgi:application". I tried that but then I get "ServiceError - Failed to deploy application." Any clues on that? -
Docker ModuleNotFoundError: No module named 'xhtml2pdf'
I've looked through several websites but I can't seem to find an answer. I'm new to django and docker and whilist building my first project which is a quotation generator, I've been looking for different ways to generate a pdf for each quote. I found a couple of tutorials on xhtml2pdf and my error appears when I try to run docker-compose up and get the following error: ModuleNotFoundError: No module named 'xhtml2pdf' I've installed xhtml2pdf using pip3 install xhtml2pdf and whenever I try to run it again I get: Requirement already satisfied: xhtml2pdf, the same for its dependencies. I've also tried pip install --upgrade --force-reinstall xhtml2pdf with no luck on my views.py file if I write from xhtml2pdf import pisa vs code gives me no errors regarding the import My requirements.txt lookslike this: psycopg2==2.9.1 pillow>=8.3 xhtml2pdf==0.2.5 reportlab==3.6.1 Dockerfile: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . -
django refresh particular table instead of whole page
I'm trying to create a search function where instead of redirecting me to another page, I want to display a table instead. here's my index.html <body> <h2>My Personal TodoApp Project</h2> <br> <form action="/searchlist/" method="get">{%csrf_token%} <input type="text" name="content" placeholder="Search a todolist" class="form-control"> <input class="button button2" type="submit" name="submit" value="Search"/> </form> <form action="/addTodo/" method="post">{%csrf_token%} <input type="text" name="content" placeholder="Add a todolist" class="form-control"/> <input class="button button" type="submit" value="Add"/> </form> # where i want my table diplay after searching a particular word <div id="searchlistdiv"></div> </body> here's the table should be displayed in index.html, I'll call it searchlistdiv.html <table> <tr> <th colspan="2">List of Todos</th> </tr> {% for result in results %} <tr> <td>{{result.content}}</td> <td><form action="/deleteTodo/{{todo_items.id}}/" style="display: inline; " method="post"> {%csrf_token%} <input class="button button1" type="submit" value="Delete"/> </form></td> </tr> {% endfor %} </tr> </table> and my views.py def searchtodolist(request): if request.method == 'GET': query = request.GET.get('content', None) if query: results = Todoitem.objects.filter(content__contains=query) return render(request, 'todoapp.html', {"results": results}) return render(request, 'todoapp.html') -
JS files not updating in python dev server
I am running a local development server with python using VS as ide through python manage.py runserver. When I update and save JS files, the views in browser do not update (even restarting the server and PC). I refreshed the cache of the browser, however it does not resolve the issue. Anyone may know the root of the problem and/or possible solution? Thanks in advance! -
Django how to update objects status in class based views?
In function based views I am using this code Notifications.objects.filter(receiver=user, is_seen=False).update(is_seen=True) for update an objects status from False to True. How to do that in class based view: here is my code: class ListNoti(ListView): model = Notifications template_name = 'notifications/notifications.html' def get_context_data(self, **kwargs): data = super(ListNoti,self).get_context_data(**kwargs) data['author_noti'] = Notifications.objects.filter(receiver=self.request.user,duplicate_value="author").order_by('-date') data['commenter_noti'] = Notifications.objects.all().filter(sender=self.request.user,duplicate_value="commenter").order_by('-date') return data I also tried this code in my class based view but didn't work. def update_noti_status(self, *args, **kwargs): noti = Notifications.objects.filter(is_seen=False).update(is_seen=True) return noti