Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
operationalError at admin/.... at most 64 tables in a join
I am facing problem operationalError at /admin... at most 64 tables in a join. I am using sqlite db. Please see code and help me. class ReagentInventory(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) manufacturing_unit = models.ForeignKey( ManufacturingUnit, on_delete=models.CASCADE) ManufacturingPlant = models.ForeignKey( ManufacturingPlant, on_delete=models.CASCADE) reagent_name = models.ForeignKey(Reagent, on_delete=models.CASCADE) storage_location = models.ForeignKey( StorageLocation, on_delete=models.CASCADE) current_stock = models.DecimalField(decimal_places=3, max_digits=10, ) measuring_unit = models.ForeignKey( MeasurementUnit, on_delete=models.CASCADE) reagent_lot_no = models.CharField(max_length=20) reagent_mother_lot_no = models.CharField(max_length=20) challan_no = models.CharField(max_length=20) mother_expiry_date = models.DateField() assigned_expiry_date = models.DateField() received_date = models.DateField() opening_date = models.DateField(blank=True) number_of_container = models.IntegerField() packing_mode = models.ForeignKey(PackingMode, on_delete=models.CASCADE) manufacturing_country = models.ForeignKey( Country, on_delete=models.CASCADE) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Reagent Inventories' def __str__(self): return self.reagent_name def __unicode__(self): return self.reagent_name Thanks -
How to insert a class in a HTML element iteratively based on a range of values
When a given page loads with a table, which is created iteratively with a for loop and a context variable, I want to change the font color of the values in a row depending in which range they are from 0 to 100%. Right now I am doing a bunch of if statements for comparison but I am looking for a better solution with javascript. This is how I am doing {% if value == 'n/a' %} <td class="class0">{{ value }}</td> {% elif similarity <= 25 %} <td class="class1">{{ value }}%</td> {% elif similarity <= 50 %} <td class="class2">{{ value }}%</td> {% elif similarity <= 75 %} <td class="class3">{{ value }}%</td> {% elif similarity <= 100 %} <td class="class4">{{ value }}%</td> {% endif %} And the class0 to class4 are the classes I am trying to insert. -
Django ImageField null=True doesn't make blank field equal to NULL
I have a model with this field: carousel_image = models.ImageField(upload_to='news/%Y/%m/%d, null=True, blank=True) I was wondering why exclude(carousel_image__isnull=True) and other queries that check if field is or isn't null aren't working. I checked my sqlite3 db and received this: sqlite> select carousel_image from asgeos_site_news; news/2020/12/23/index.jpeg news/2020/12/23/gradient-1.jpeg ( 3 blank lines ) I also tried adding WHERE carousel_image = NULL and it returned nothing. Why my images are not null? They're just a blank lines. I have to use carousel_image__exact='' to exclude them right now. -
open redirect bug in django 2.2 on chrome browser?
I have a url which is supposed to do the redirects to the allowed hosts only after login. but when I am tying to login using https://example.com/login/?redirect_to=/%09/stackoverflow.com which checks the condition of allowed urls to be redirected using is_safe_url https://github.com/django/django/blob/2.2.17/django/utils/http.py#L295 it is redirecting me to stackoverflow which it should not. And this is happening only in chrome. Here :https://github.com/django/django/blob/2.2.17/django/utils/http.py#L386 it checks for the Control characters but it doesn't seem to work (%09 is a control character) -
How to deploy reactjs and django webpack in azure webapp
I used ReactJS web-pack for frontend and Django django-webpack-loader . It is working fine in localhost. But when I reployed into production index page {% render_bundle 'main' %} bundle.js file showing html code only. So I'm getting uncaught syntaxerror unexpected token <. -
How to run makemigrations for dockerized django app
I have been trying to setup a django app using this guide: https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/ And it was a great resource to get everything up and running. However i have problem now when it comes to migrations. Say i add a model, add data into my db, and later i change the model. Now i can run makemigrations using the exec method on the container, but when i shut down my migrations are not stored in my local files i save to my git project, instead they are lost as i spin down the container. Does anyone know how to solve this, how do you makemigrations is such a setup where you run two dockerized django/postgres dev/prod environments? -
(Django - Python) Hidden Input Request to views.py
I have to create a site with auctions and I have an homepage which shows all the auctions active... I want to redirect users to auctions details clicking on relative button but I have some problems with the hidden input request because it doesn't report the hidden value to my function ( def bid (request, auction) ) but I see it on the url bar after the csrfmiddlewaretoken (id=1), can you help me? (I have tried also with POST request...) These are my codes: views.py def home(request): auctions = Auction.objects.filter(status=True) form = detailForm(request.GET or None) if request.method == "GET": id = request.GET.get("id") if form.is_valid(): [bid(request,auction) for auction in auctions if auction.id==id] else: form = detailForm() return render(request, "index.html", {"auctions":auctions, "form":form}) forms.py class detailForm(forms.ModelForm): class Meta: model = Auction fields = ("id",) index.html {% for auction in auctions %} <--! I put all the informations about auctions --> <form method="GET"> {% csrf_token %} <input type="hidden" name="id" value={{auction.id}}> <input type="submit"> {% endfor %} </form> Thanks to everyone! -
how it is not getting request object in django serializer after getting it(printing it)
I'm sending request from views.py in context to serializers.py As you can see in ServiceCatagorySerializer() Views.py @api_view(['GET']) def mainPageData(request): if request.method=='GET': data = {} data['ServiceCatagories']=ServicesCatagorySerializer(ServicesCatagory.objects.all(), many=True, context={'request':request}).data data['Plans']=PlansSerializer(Plans.objects.filter(Open=True), many=True).data data['FrontPageFeedback']=FrontPageFeedbackSerializer(FrontPageFeedback.objects.filter(Type='Good'), many=True).data return Response(data) and in serializers.py class ServicesCatagorySerializer(serializers.ModelSerializer): Image = serializers.SerializerMethodField() class Meta: model = ServicesCatagory fields = ('id','Name','Image','Description','get_absolute_url') def get_Image(self, ServicesCatagory): request = self.context.get('request') image_url = ServicesCatagory.Image.url print() print() print() print(dir(request)) print() print() print() return request.build_absolute_uri(image_url) after that in cosole i'm getting the output of print(dir(request)) output in console but after getting data got an error of NonType i got that also in console. -
ForeignKey with where cluase in django model
I am a newer person in Django. I face a challenge with Foreign key in Django model. I have 3 models like this: class A(models.Model): emp=models.CharField(max_length=20) class B(models.Model): type = models.OneToOneField(A, on_delete=models.CASCADE) class C(models.Model): emp_type=models.ForeignKey(B, on_delete=models.CASCADE) in Admin panel when I want to chose a data for inserting in database a DropdownBox shows all the B model but I'd like to show only specific data on B model in C model not all the data. How could I solve this problem? -
Why am I getting MultiValueDictKeyError: on 'date' even my form suppose to have 'date'
I am making a very simple web application where users encounter a form in which they can select a origin,destination (both are airports) and a date for their travel. I only have one form in forms.py: from django.forms import ModelForm,DateField,ChoiceField from .models import Flight from django.forms.widgets import SelectDateWidget,TextInput from datetime import datetime from .skyscanner import list_airports airports = list_airports() class FlightForm(ModelForm): origin = ChoiceField(required=True, choices = airports) destination = ChoiceField(required=True, choices = airports) class Meta: model = Flight fields = ['origin', 'destination', 'date'] widgets = { 'date': SelectDateWidget(years=[2021,2022]), } Where I declaratively define 'origin' and 'destination' while 'date' is coming from Flight model but represented as SelectDateWidget. Here is my models.py : from decimal import Decimal from django.contrib.auth.models import AbstractUser from django.db import models from . import fields class User(AbstractUser): pass class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals") price = fields.DecimalRangeField(min_value=Decimal( '0.00'), decimal_places=2, max_digits=10) date = models.DateTimeField() def __str__(self): return f'From {self.origin} to {self.destination} at {self.date}' And the index view: def index(request): if request.method == 'POST': origin=Airport.objects.get(code=request.POST['origin']) destination=Airport.objects.get(code=request.POST['destination']) form = FlightForm(initial={'origin': origin, 'destination': destination, 'date': request.POST['date']}) if form.is_valid(): flight={} flight['origin'] = form.cleaned_data['origin'] … -
How to implement date range filter in Django Admin using nonexistent field?
I would like to implement date range filtering on a model in Django Admin by a value which does not actually exist in the model as a field. I want to use the date range picker like DateRangeFilter from the django-admin-rangefilter package. Assume, the model has the date field and we would like to display objects, for which date - 7 lies between the specified range (just an artificial example). I have created a custom field class. class CustomDateFilter(DateRangeFilter): title = "custom_date" def queryset(self, request, queryset): queryset = super(request, queryset) queryset = queryset.annotate(custom_date=F("date") - 7) return queryset But it's usage leads to either the FieldDoesNotExist ... error if used so: @admin.register(SomeModel) class SomeModelAdmin(admin.ModelAdmin): list_filter = [("custom_date", CustomDateFilter)] or SystemCheckError: System check identified some issues: ERRORS: <class '...SomeModelAdmin'>: (admin.E114) The value of 'list_filter[0]' must not inherit from 'FieldListFilter'. if used so: @admin.register(SomeModel) class SomeModelAdmin(admin.ModelAdmin): list_filter = [CustomDateFilter] How can I achieve the thing I want to do? -
How build AJAX in follow user functionality
I have big challange with AJAX. I made 'Follow User' functionality and don't know how implement AJAX for this... This is my code: In models.py i have: class UserFollowing(models.Model): following_from = models.ForeignKey("Profile", related_name="following_from", on_delete=models.CASCADE) follow_to = models.ForeignKey("Profile", related_name="follow_to", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: db_table = 'users_userfollowing' constraints = [models.UniqueConstraint(fields=["following_from", "follow_to"], name="unique_followers")] ordering = ("-created",) def __str__(self): return f"FROM:{self.following_from} TO:{self.follow_to}" class Profile(AbstractUser, HitCountMixin): slug = models.SlugField(null=False, unique=True) following = models.ManyToManyField("self", through=UserFollowing, related_name="followers", symmetrical=False) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.username) return super().save(*args, **kwargs) In view.py I made function to follow user: def follow_user(request): user = request.user if request.method == 'POST': user_id = request.POST.get('user_id') user_obj = Profile.objects.get(id=user_id) if user not in user_obj.followers.all(): UserFollowing.objects.get_or_create(following_from=user, follow_to=user_obj) else: UserFollowing.objects.filter(following_from=user, follow_to=user_obj).delete() return redirect('profile', slug=user_obj.slug) And in urls.py urlpatterns = [ path("followers/", follow_user, name="follow_user"), ] At least my html template: {% with total_followers=profile.followers.count %} ({{ total_followers }} Follower) <br> {% endwith %} <form action="{% url 'users:follow_user' %}" method="POST" class="follow-form" id="{{ profile.id }}"> {% csrf_token %} <input type="hidden" name="user_id" value="{{ profile.id }}"> <button type="submit" class="follow-btn{{ profile.id }}"> {% if request.user not in profile.followers.all %} Follow {% else %} Unfollow {% endif %} </button> This works very good. I can follow anad unfollw user … -
How can I access my sqlite3 database through the html template using Django?
I have a Django application where most of my backend code is in views.py. In the frontend, I'm using an html template, but currently I have hardcoded options that the user can choose from a drop down menu. Those hardcoded options are all available in the sqlite3 database which is used extensively in views.py. Is there a way that I read those fields of database from the html file directly instead of hardcoding them? -
How to add a dynamic value in settings.py Django
I want to maintain a variable TOKEN in my settings.py of my django project, and it changed with time. The token saved at db like: class FbBmToken(models.Model): manager_name = models.CharField(max_length=64) token = models.CharField(max_length=255, blank=True, null=True) effective = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'fb_bm_token' And I want use it in my django project anywhere by from django.conf import settings token = settings.TOKEN How can I make this happen? Greate thanks -
PostGIS on WSL2 - extension "postgis" has no installation script nor update path for version
I am trying to add PostGIS extension to a postgresql database on my WSL2 (with Ubuntu 20.04) for a django project. I have already installed postgresql, postgis and all dependencies with the following: sudo apt -y install postgresql-12 postgresql-client-12 sudo apt install postgis postgresql-12-postgis-3 sudo apt-get install postgresql-12-postgis-3-scripts And everything worked fine. In postgresql, I have already created my db and connected to it: sudo -u postgres psql -p 5432 -h 127.0.0.1 postgres=# CREATE DATABASE dbname; postgres=# \c dbname; But then, when I try to add the postGIS extension with: postgres=# CREATE EXTENSION postgis; I get the following error: ERROR: extension "postgis" has no installation script nor update path for version "3.0.0" And despite searching for similar questions on stackoverflow, I couldn't find any satisfactory solution for my case. Any idea what it could be wrong and how I can solve it? thank you! -
django configure apache to serve media and static files
So I have apache and mod-wsgi installed on windows. Now I need to configure apache to serve django's media files. urls.py from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('api/', include('api_backend.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) apache httpd.conf LoadModule wsgi_module "c:/users/iyapp/pycharmprojects/cloud_server/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win32.pyd" ... # custom httpd configuration WSGIPythonPath "c:/users/iyapp/pycharmprojects/cloud_server" WSGIPythonHome "c:/users/iyapp/pycharmprojects/cloud_server/venv" <VirtualHost *:80> ServerName localhost WSGIScriptAlias / "c:/users/iyapp/pycharmprojects/cloud_server/rebox_django/wsgi.py" Alias /media/ "c:/users/iyapp/pycharmprojects/cloud_server/media/" Alias /static/ "c:/users/iyapp/pycharmprojects/cloud_server/static/" <Directory "c:/users/iyapp/pycharmprojects/cloud_server/static"> Require all granted </Directory> <Directory "c:/users/iyapp/pycharmprojects/cloud_server/media"> Require all granted </Directory> <Directory "c:/users/iyapp/pycharmprojects/cloud_server/rebox_django"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> This is what I have so far. However, when I try to access a media file that the server has, I get a 404 not found error. Why is that? Can someone please help me? I am using Apache24 (32 bits with python) and the mod-wsgi python module. settings.py ROOT_URLCONF = 'rebox_django.urls' WSGI_APPLICATION = 'rebox_django.wsgi.application' STATIC_URL = '/static/' STATICFILES_DIRS = [] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') STATIC_ROOT = os.path.join(BASE_DIR, "static/") -
Python Django arrangement of posts within a category?
I wanted some help from you, if it is possible, I am working in Django, I was trying to arrange the posts in the template, but without success, so far I have displayed the posts in the template. order_by ('-data_e_postimit') the same I want to function in posts Within a category. class LajmetListView(ListView): model = Kategori model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmet' def get_context_data(self, **kwargs): context = super(LajmetListView, self).get_context_data(**kwargs) context['lajmet'] = Lajmet.objects.order_by('-data_e_postimit') context['trilajmet'] = Kategori.objects.get(pk=1) context['katego'] = Kategori.objects.all() return context <div class="slick_slider"> {% for lajmet in trilajmet.lajmet_set.all %} {% if forloop.counter < 5 %} <div class="single_iteam"> <a href="{% url 'lajme-detail' lajmet.slug %}"> <img src="media/{{lajmet.fotografit}}" alt=""></a> <div class="slider_article"> <h2><a class="slider_tittle" href="{% url 'lajme-detail' lajmet.slug %}">{{lajmet.titulli}}</a></h2> <p>{{lajmet.detajet|safe}}</p> <p>{{lajmet.data_e_postimit|date:"F d, Y H:i"}}</p> </div> </div> {% endif %} {% endfor %} -
Reverse for 'post_like_dislike' with arguments '('',)' not found. 1 pattern(s) tried: ['post_like_dislike/(?P<post_id>[0-9]+)/$']
I am building a Blogapp and Adding like , unlike buttons into it. BUT when i trying to open page, i keep getting this error. Reverse for 'post_like_dislike' with arguments '('',)' not found. 1 pattern(s) tried: ['post_like_dislike/(?P<post_id>[0-9]+)/$'] views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:posts') urls.py path('post_like_dislike/<int:post_id>/',views.post_like_dislike, name='post_like_dislike'), show_more.html <div class="card-footer"> <form method="GET" class="likeForm d-inline" action="{% url 'mains:post_like_dislike' post.id %}" data-pk="{{post.id}}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{post.id}}"> {% if user in post.likes.all %} <p style="color:#065FD4;display: inline">{{post.likes.count}}</p> {% else %} <p style="color:black;display: inline">{{post.likes.count}}</p> {% endif %} </span> Like</button> </form> <form action="{% url 'mains:post_like_dislike' post.id %}" method="GET" class="d-inline dislikeForm" data-pk="{{ post.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-down"></i> <span id="id_dislikes{{post.id}}"> {% if user in post.dislikes.all %} <p style="color:#065FD4; display: inline;">{{post.dislikes.count}}</p> {% else %} <p style="color:black; display: inline;">{{post.dislikes.count}}</p> {% endif %} </span> Dislike </button> </form> </div> I don't what am … -
django redirect under post statement doesn't work
This is the exmaple code that works, or any other if statements def login_page(request): if request.user.is_authenticated: return redirect('home') return render(request, 'Page-2.html') def home(request): return render(request, 'Page-1.html') But when I change the redirect under a request.method =='POST' statement, it doesn't redirect the page, but the print works def login_page(request): if request.user.is_authenticated: return redirect('home') if request.method == 'POST': print('test') return redirect('home') return render(request, 'Page-2.html') def home(request): return render(request, 'Page-1.html') urls of the project from django.contrib import admin from django.urls import path from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('login.urls')), ] urls of the app from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('login/', views.login_page, name='login'), path('home/', views.home, name='home') ] The original code was just for login and redirect the page, did I miss something to set up? thanks! -
Unable to view database on frontend in Django via Shell
Hello wonderful people. I am currently learning Django and trying to display the database which is created via form on inventiory_view.html I am unable to do so via shell scripting. I am able to display the objects via shell terminal but whenever I use the same command which is Form1.objects.all I am unable to display it on my desired html page. I would really appreciate your help in this matter. Thanks in advance This is the form1.html where I am getting the data from the user. {% extends 'base.html' %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% block title %} Title of Form1 {% endblock %} </head> {% block body %} <div class="container"> <h1>Form1</h1> <form method="POST" action=" /form1/"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Item name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "item" placeholder="laptop"> </div> <!-- <div class="form-group"> <label for="exampleFormControlInput1">Quantity </label> <input type="number" class="form-control" id="exampleFormControlInput1" name= "quantity" placeholder="1,2,3"> </div> --> <div class="form-group"> <label for="exampleFormControlSelect1">Quantity</label> <select class="form-control" input type="number" id="exampleFormControlSelect1" name= "quantity"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group"> <label for="exampleFormControlInput1">Vendor name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name= "vendor" placeholder="Nokia"> </div> … -
Python qrcode does not work inside docker
My django application generates a qrcode in the models everytime a new item is added through the form. It works perfectly fine when I run it using the python manage.py runserver command but when I dockerize the application, it shows the following error: qr_codes_img = qrcode.make(self.bag_asset_id) AttributeError: module 'qrcode' has no attribute 'make' This only happens when I build and run the docker file, otherwise it works fine. I do not have any other file or function by the name 'qrcode' and the requirements.txt file is updated perfectly. My Dockerfile looks like this: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install -y gconf-service libasound2 libatk1.0-0 libcairo2 libcups2 libfontconfig1 libgdk-pixbuf2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libxss1 fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app -
How to create model with 2 columns unique together and autoincrement?
I have two columns in my Invoice model in Django: class Invoice(models.Model): use_in_migrations = True year = models.CharField(max_length=16, default='') index = models.IntegerField(default=0) with which I want to achieve in the database this sequence: ... 2020, 134 2020, 135 2021, 1 2021, 2 ... First I tried to add class Meta: unique_together = [['prefix', 'index']] so I will be sure that I get always unique row values in columns. The issue is that with PostgreSQL, this creates this sequence: ... 2020, 134 2020, 135 2021, 136 2021, 137 ... Any solution how to solve this in Django? I am using Django 2.2... -
How to call a function in django admin to refresh data available?
I want to refresh all data under all source fields in django admin. Below is my ModelAdmin class SourceAdmin(admin.ModelAdmin): list_display= ('id','source_name','missing_data','modified_date_missing','refresh_data','email_refresh_days','modified_date_refresh','search_appearance','modified_date_search','date_added','date_modified','email_count','refresh','stop') search_fields = ['id','source_name','email_refresh_days'] ordering = ['-date_modified'] list_editable = ['missing_data','refresh_data','search_appearance','email_refresh_days'] list_filter = [SourceidFilter, SourcenameFilter] def refresh(self, obj): return mark_safe('<input type="button" value="start">') def stop(self, obj): return mark_safe('<input type="button" value="stop">') def set_refresh(self, request): self.model.objects.all().update(refresh_data=True) self.message_user(request, "All data are now refreshed") return HttpResponseRedirect("../") def set_stop(self, request): self.model.objects.all().update(refresh_data=False) self.message_user(request, "All data are now stopped") return HttpResponseRedirect("../") def save_model(self, request, obj, form, change): if 'missing_data' in form.changed_data: obj.modified_date_missing = timezone.now() if 'refresh_data' in form.changed_data: obj.modified_date_refresh = timezone.now() if 'search_appearance' in form.changed_data: obj.modified_date_search = timezone.now() obj.modified_by = request.user obj.save() I want to call set_refresh and set_stop function using below functions when i will click start and stop which i mentioned in list_display. It should refresh data available in refresh_data one by one. def refresh(self, obj): return mark_safe('<input type="button" value="start">') def stop(self, obj): return mark_safe('<input type="button" value="stop">') Start and Stop Button -
Django POST form with 2 submit buttons, "enter" behavior
I have a form with 2 submit buttons that look like this: <select class="form-select" name="modelsz" id="modelsz"> <option selected>{{found_model}}</option> {% for i_model in searched_model %} <option>{{i_model}}</option> {% endfor %} </select> <button type="submit" name="chooseModel" class="btn btn-outline-success" value="Confirm">Confirm</button> ... <input type="text" class="form-control" placeholder="Symbol" name="symbolsz" id="symbolsz" value={{found_symbol}}> <button type="submit" name="searchProduct" class="btn btn-outline-success" value="Search">Search</button> There is no problem in handling both of them in one form but I can't figure out how to change default button when using "enter" key on my keyboard. Every time I press "enter" it chooses first button -
Implementing django-rest-passwordreset to React Native
I'm trying to add change password functionality to a Django / React app. I'm using django-rest-passwordreset library for creating Reset or Forgot Password API using Django Rest Framework. After I type the email that registered, I've managed get the token from the console But I'm struggling to find a way to send an email to their email address with the link to reset their password along the given token. I've tried the SMTP Method or SendGrid. Was trying this way and this way Can someone show me the correct way to make this work? Thanks a lot.