Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Command errored out with exit status 1' getting this error message while installing mysql client in python
(env) C:\Users\shreya kumar\Documents\django website\audit_website>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\shreya kumar\documents\django website\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\shreya kumar\AppData\Local\Temp\pip-record-npl_lx21\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\shreya kumar\documents\django website\env\include\site\python3.9\mysqlclient' cwd: C:\Users\shreya kumar\AppData\Local\Temp\pip-install-7l4hf6a3\mysqlclient\ Complete output (23 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.9\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.9\MySQLdb creating build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.9\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.9\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\shreya kumar\documents\django website\env\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\shreya kumar\\AppData\\Local\\Temp\\pip-install-7l4hf6a3\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record … -
Form to appear in a popup panel
I have the following file setup: In forms.py class TableCheckInForm(forms.Form): guest_count = forms.IntegerField(min_value =0) In views.py: def table_checkin_view(request): if request.method == 'POST': form = TableCheckInForm(request.POST) if form.is_valid(): cd = form.cleaned_data else: form = TableCheckInForm() return render(request, 'table/table_checkin.html', {'form': form}) In the template table_view.html <script src="{% static 'js/table.js' %}"></script> ... <button class="button checkin_button" onclick="openForm()">Check In</button> ... In another template table_checkin.html {% load static %} <script src="{% static 'js/table.js' %}"></script> <div id="table_checkin_form"> <h1>Check-In</h1> <form class="form-container" method="post"> {{ form.as_p }} {% csrf_token %} <button type="submit" class="table_checkin" onclick="closeForm()">Check In</button> </form> </div> In static Javascript file table.js function openForm() { document.getElementById("table_checkin_form").style.display = "block"; } function closeForm() { document.getElementById("table_checkin_form").style.display = "none"; } In urls.py urlpatterns = [ ... path('', views.table_view, name='table_view'), path('1/checkin/', views.table_checkin_view, name='table_checkin_view'), ... ] I am trying to implement a popup panel that contains the form above, similar to this example from W3Schools here. Suppose I am currently on the template table_view.html. When I click the button checkin_button, I would like to have the form popup in a small panel that renders table_checkin.html. That means, in the background, I would like still see the template table_view.html. But the form in my case always appear in a completely new page. Putting aside the css effect, … -
django-summernote is not editable on Django admin page
Currently I am trying to implement django-summernote to my Django project. I could pip-install it, set up the urls.py, setting.py, admin.py but it is not working properly on admin page. If I go to the page, the information is displayed but it is not editable. Does anybody know how to fix this? Here is the info about package versions. Python 3.6.9 Django 2.1 django-summernote 0.8.11.6 And here is the screenshot image of the admin page. The data is displayed but the none of buttons for html customization is displayed, and this is not editable. I can not modify any sentence. I would really appreciate if somebody gave me any advice on this. Details package info↓ (This is result of "pip list") asgiref 3.2.10 beautifulsoup4 4.9.3 bs4 0.0.1 cachetools 4.1.1 certifi 2019.6.16 chardet 3.0.4 cssselect2 0.3.0 cycler 0.10.0 decorator 4.4.1 Django 2.1 django-bootstrap4 1.1.1 django-cleanup 4.0.0 django-filter 2.4.0 django-modelcluster 5.1 django-pandas 0.6.1 django-summernote 0.8.11.6 django-taggit 1.3.0 django-treebeard 4.3.1 djangorestframework 3.12.1 draftjs-exporter 2.1.7 et-xmlfile 1.0.1 google-api-core 1.22.2 google-api-python-client 1.11.0 google-auth 1.21.1 google-auth-httplib2 0.0.4 googleapis-common-protos 1.52.0 gspread 3.2.0 html5lib 1.1 httplib2 0.17.0 idna 2.8 importlib-metadata 1.7.0 jdcal 1.4.1 Jinja2 2.10.1 kiwisolver 1.2.0 l18n 2018.5 lxml 4.4.1 MarkupSafe 1.1.1 matplotlib 3.2.1 mplfinance 0.12.3a3 mysqlclient … -
Error: NoReverseMatch: Reverse for 'index' not found. 'index' is not a valid view function or pattern name
I'm developing websystem in Django, when I write a login function gives me this error: NoReverseMatch at /login/ Reverse for 'index' not found. 'index' is not a valid view function or pattern name. I checked the code a hundred times but there is something I'm missing and can't find the solution. I've been stuck on this for a while, can't seem to fix this error. The other parts from the website are working fine. views.py @login_required def index(request): return render(request, 'dashboard.html') def loginPage(request): form = AuthenticationForm() if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) if request.GET.get('next'): return redirect(request.GET.get('next')) else: return redirect('index') return render(request, 'login.html', {'form': form}) urls.py: urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('', views.index, name="index"), ] login.html <body> <div class="container h-100"> <div class="d-flex justify-content-center h-100"> <div class="user_card"> <div class="d-flex justify-content-center"> <h3 id="form-title">Login</h3> </div> <div class="d-flex justify-content-center form_container"> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <div class="d-flex justify-content-center mt-3 login_container"> <input class="btn login_btn" type="submit" value="Login"> </div> </form> </div> </body> dashboard.html {% extends 'main.html' %} {% block content %} <br> <div class="row"> <div class="col-md-10"> <h5>Patients:</h5> <hr> <a class="btn btn-sm" href="">+ Create Patient</a> <div class="card card-body"> … -
why do I get a single field value in Django formset_factory?
when I checked formset_factory validation and get fields to value from formset it returns only one field value in formset. But I can not find any problem in my code. please help me to solve the problem. My form.py: class SbTitleForm(forms.Form): sb_title = forms.CharField(required=False) sb_permission = forms.BooleanField(required=False) SbTitleFormSet = formset_factory(SbTitleForm, extra=0) My view.py: def menuuser(request): sbtitle = SbTitle.objects.all().values() sbtitle_form = SbTitleFormSet(initial=sbtitle) if request.method == 'POST': sbtitle_form = SbTitleForm(request.POST, initial=sbtitle) if sbtitle_form.is_valid(): print(sbtitle_form.cleaned_data) context = { 'user_role':user_role, 'sbtitle_form':sbtitle_form, } return render(request, 'admins/user_role/user_permission.html', context) My HTML: {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} {{ sbtitle_form.management_form }} {{ sbitleelement_form.management_form }} <div id="DataTables_Table_2_wrapper" class="dataTables_wrapper no-footer"> <div class="datatable-scroll"> <table class="table table-bordered table-hover datatable-highlight dataTable no-footer" id="DataTables_Table_2" role="grid" aria-describedby="DataTables_Table_2_info"> <thead> <tr role="row" class="bg-teal-400"> <th class="sorting text-center h5" tabindex="0" aria-controls="DataTables_Table_2" rowspan="1" colspan="1" aria-label="Job Title: activate to sort column ascending">Sidebar Title</th> </tr> </thead> <tbody> {% for field in sbtitle_form %} <tr role="row" class="odd"> <td class="sorting_1 text-center"><h4>{{ field.sb_title.value }} {{ field.sb_permission }}<p class="text-danger">{{ field.errors.as_text }}</p></h4></td> {% endfor %} </tbody> </table> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Save</button> </div> </div> </form> </div> {% endblock %} when I try to print(sbtitle_form.cleaned_data) its return only one field … -
Django ORM: filtering over a primary key returning 2 objects
How is it possible for a ModelName.objects.get(id=XX) to return more than object when the model use the auto generated id field as the one and only primary key? TLDR; Exception: MultipleObjectsReturned: get() returned more than one XXX -- it returned 2! View: django.views.generic.DetailView Lookup field left unchanged and defaults to the auto created id field on model View class ProjectFilePreviewView(ProjectFilePermissionMixin, DetailView): template_name = "project_file_preview.html" model = ProjectFile def get(self, request, *args, **kwargs): pk = int(kwargs.get('pk')) redirect = False current = self.get_object() # <-- error here ... return super().get(request, *args, **kwargs) Model class XXX(models.Model): xx = models.ForeignKey( 'xxx', related_name='x', null=True, blank=True, verbose_name=_('xx')) xxx = models.ForeignKey(User, verbose_name=_('xx'), null=True, on_delete=models.SET_NULL) xxxx = models.FileField(_('xx'), max_length=512, upload_to=xx) xxxxx = models.ImageField(_('xx'), null=True, blank=True, max_length=512, upload_to='xx/') created_at = models.DateTimeField(_('created at'), auto_now_add=True) xxxxxx = models.DateTimeField(_('xx'), null=True, blank=True) Traceback MultipleObjectsReturned: get() returned more than one xxx -- it returned 2! File "django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "django/contrib/auth/mixins.py", line 56, in dispatch return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "django/views/generic/base.py", line 88, in dispatch return handler(request, … -
Get user from refresh token in Django Simple JWT's TokenRefreshView
I am trying to check if the user still exists when Refreshing the Token, returning the user's updated detail (if updated) upon refreshing a token. Is there anyway to retrieve the user's details from the refresh token? [request.user] is currently marked as AnonymousUser so I am unable to know who the refresh token belongs to. -
Passing date format to field in django
I working on an "edit profile page" where users can edit their information, but I am facing a problem displaying users birth date. Sidenote: The html input type="date" accepts date input in the format "YYYY-mm-dd" but displays it in the format "dd-mm-YYYY" The problem is that when I do this it displays the date fine: ... <input type="date" value={{ user.profile.birth_date|date:'Y-m-d }}> ... but when I do this it doesn't, and display nothing, it just says dd/mm/yyyy <form method="POST"> {% csrf_token %} {% for field in form %} {{ field.label_tag }} {{ field }} {% endfor %} </form> How can I pass the field the value of the birth date in the format "YYYY-mm-dd" -
I can't figure out how to test these views using unittests
I need to test this code using unittest help me figure it out show how they are tested def post(self, request, pk): form = ReviewForm(request.POST) movie = Movie.objects.get(id=pk) if form.is_valid(): form = form.save(commit=False) if request.POST.get("parent", None): form.parent_id = int(request.POST.get("parent")) form.movie = movie form.save() return redirect(movie.get_absolute_url()) -
I can not install psycopg2 gives an error what to do
I can not install psycopg2 gives an error what to do I just started to study and already such traps help File "C:\Users\МК\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\postgresql\base.py", line 29, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: DLL load failed while importing _psycopg: Не найден указанный модуль. -
Connection Refused to Minio Docker instance from my Django Application
Hi im trying to connect to my Minio instance which is running inside a docker container from a django instance, which is also running inside a docker container. I keep getting this error: 2020-10-29 13:59:17,568 urllib3.util.retry DEBUG Incremented Retry for (url='/'): Retry(total=0, connect=None, read=None, redirect=None, status=None) 2020-10-29 13:59:20,773 urllib3.connectionpool WARNING Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1076)'))': / 2020-10-29 13:59:20,774 urllib3.connectionpool DEBUG Starting new HTTPS connection (6): minio:9000 My docker-compose file is the following: version: "3.7" services: db: container_name: db image: mariadb restart: always ports: - '3306:3306' environment: MYSQL_DATABASE: 'django_dev' MYSQL_USER: 'user' MYSQL_PASSWORD: 'password' MYSQL_ROOT_PASSWORD: 'password' volumes: - ./mariadb:/var/lib/mysql minio: container_name: minio image: minio/minio command: 'server /export' environment: MINIO_ACCESS_KEY: weak_access_key MINIO_SECRET_KEY: weak_secret_key ports: - '9000:9000' volumes: - ./minio:/export web: container_name: web build: context: ./django/ dockerfile: ./Dockerfile target: dev command: python manage.py runserver 0.0.0.0:8000 volumes: - ./django:/usr/src/app ports: - "8000:8000" env_file: - ./.env.dev depends_on: - minio - db phpmyadmin: container_name: db_viewer image: phpmyadmin/phpmyadmin restart: always ports: - '8080:80' environment: PMA_HOST: db MYSQL_ROOT_PASSWORD: 'password' depends_on: - db The code to set up the client: minioClient = Minio('minio:9000', access_key='weak_access_key', secret_key='weak_secret_key') minioClient.list_buckets() Im using WSL2 as development environment. Python Version 3.7.7, Django Version 3.1.2, … -
Django Class based views - Signup
I have implemented a SignUp/SignIn based on class based views. While the Login is working fine, Sign up it does not. The problem is that after trying to register user and POST method is 200, user is not created in database. BTW I think the problem is on the FrontEndbecause when i'm using a simple html file with {{ form.as_p }} it works when i'm using a template from internet it does not. Please help me to identify the reason: views.py file from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserResisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/register.html' success_url = reverse_lazy('login') success_message = "Your profile was created successfully" authapp1/urls.py file from django.urls import path from .views import UserResisterView urlpatterns = [ path('register/', UserResisterView.as_view(), name='register'), ] auth/urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), # Django authentication system with package URLs path('authapp1/', include('django.contrib.auth.urls')), path('authapp1/', include('authapp1.urls')), html template <!-- Register --> <section class="our-log-reg bgc-fa"> <div class="container"> <div class="row"> <div class="col-sm-12 col-lg-6 offset-lg-3"> <div class="sign_up_form inner_page"> <div class="heading"> <h3 class="text-center">Register to start learning</h3> <p class="text-center">Have an account? <a class="text-thm" href="{% url 'login' %}">Login</a></p> </div> <div … -
Excel file downloaded through Django's StreamingHttpResponse shows 'invalid format' on opening
Django 2.2.5 | Python 3.6.12 I'm trying to create an xlsx file for download using a list of dictionaries through pandas. Since the file can become huge, I'm using StreamingHttpResponse() instead of normal HttpResponse(). The code that I have currently downloads the file but shows file format is invalid when I try and open it. I have referred to these two links as of now: https://docs.djangoproject.com/en/3.1/howto/outputting-csv/#streaming-large-csv-files Django Pandas to http response (download file) Here's the code that I am using currently: # 'emails' is the list of dictionaries # 'list_name' contains the name of file with BytesIO() as bio: writer = pd.ExcelWriter(bio, engine='xlsxwriter') dataframe = pd.DataFrame(data=emails) dataframe.to_excel(writer, sheet_name="Verify Results") writer.save() bio.seek(0) workbook = bio.getvalue() response = StreamingHttpResponse( workbook, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) response['Content-Disposition'] = f"attachment; filename={list_name}.xlsx" return response However, if I use response = HttpResponse( bio, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ) it downloads and opens up correctly. How do I use StreamingHttpResponse with pandas so that it downloads correctly? -
DJANGO PostgreSQL Query Issue
I have the following query in my two views. Here is both my views code. The query works fine in my NHS view but in my K-8 View it will not pull K-8 & NHS events when I run the query. The interesting thing is this works fine on my development server running SQL-Lite. So this is obviously a PostgreSQL issue. Appreciate any help on this. Thank you. @login_required @allowed_users(allowed_roles=['Admin', 'Administration','Teachers']) def K8Calendar(request): if request.method == "GET": calendar_events = PendingApprovalEvents.objects.filter(calendar = "K-8", approved = 1).order_by("-start_date") or PendingApprovalEvents.objects.filter(calendar = "K-8 & NHS", approved = 1).order_by("-start_date") userid = request.user.id print(calendar_events) my_filter = K8CalendarFilter(request.GET, queryset = calendar_events) calendar_events = my_filter.qs return render(request, 'eventscalendar/k8calendar.html', {'userid': userid, 'calendar_events':calendar_events, "my_filter": my_filter}) @login_required @allowed_users(allowed_roles=['Admin', 'Administration','Teachers']) def NHSCalendar(request): if request.method == "GET": calendar_events = PendingApprovalEvents.objects.filter(calendar = "NHS", approved = 1).order_by("-start_date") or PendingApprovalEvents.objects.filter(calendar = "K-8 & NHS", approved = 1).order_by("-start_date") userid = request.user.id my_filter = K8CalendarFilter(request.GET, queryset = calendar_events) calendar_events = my_filter.qs return render(request, 'eventscalendar/nhscalendar.html', {'userid': userid, 'calendar_events':calendar_events, "my_filter": my_filter}) -
How get image from images model to home page in django?
I am developing an ecommerce website with django. In my home page displayed product cards as you see in below image. enter image description here This product image in each card I take from my Product model (image field). When I hover over this image in home page, image is changing to other image. That is for I need other image, and I want take next image (display when I hover over) from my Product_images model. But I dont know how do that. Please help me. urls.py from django.urls import path from . import views from django.conf.urls.static import static urlpatterns = path('', views.home_page, name='amd-home'), path('product/<int:id>/', views.product_detail, name='product-detail'), path('about/', views.about, name='amd-about'), ] views.py from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView from django.http import HttpResponse from .models import Product, Product_image, Product_details def home_page(request): products = Product.objects.all() images = Product_image.objects.all() context = {'products':products, 'images':images} return render(request, 'product/home.html', context) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=200) parent_id = models.IntegerField(default=0) description = models.TextField() image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Brand(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=400) image = models.ImageField(upload_to='uploads/') def __str__(self): return f'{self.name}' class Product(models.Model): title = models.CharField(max_length=200) image … -
Trying to get JSON data from POSTGRESQL in Django in localhost
I and my friends are doing a project and now it is time to merge our postgresql databases and I need to grab everything from mine and send it as a JSON file. As a programming newbie, I do not wanna mess up my database since I have done it once and was wondering what would be the easiest way to grab everything from http://127.0.0.1:8000/admin/ as a JSON file. I currently have the home page and the footer information created and can be controlled from the admin page and need those data. def home(request): if request.method == 'POST': form = ContactForm(request.POST or None) if form.is_valid(): sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) send_mail('New Enquiry', message, sender_email, ['warp.dev.group@gmail.com']) return HttpResponse('Thanks for contacting us!') else: form = ContactForm() context = { "homepage": HomePage.objects.filter(name="homepage").first(), "footer": Footer.objects.filter(name="footer").first(), 'form': form } return render(request, 'member/home.html', context) class Footer(models.Model): name = models.CharField(max_length=20, blank=True) description = models.CharField(max_length=50, blank=True) contact_number = models.IntegerField(blank=True) facebook = models.URLField(max_length=50, blank=True) twitter = models.URLField(max_length=50, blank=True) instagram = models.URLField(max_length=50, blank=True) email = models.EmailField(max_length=30, blank=True) footer_data = models.CharField(max_length=30, blank=True) terms_and_conditions = models.URLField(max_length=250, blank=True) faq = models.URLField(max_length=250, blank=True) def __str__(self): return f'{self.name}' class HomePage(models.Model): name = models.CharField(max_length=10, blank=True) … -
Django/jQuery- get submit button value from multiple buttons
I have the next submit buttons inside a post form: <div class="col-md-4 col-sm-4"> <button type="submit" class="btn btn-default btn-block" value="True" id="subButton" name="is_attending" onclick="FbotonOn()">Yes, i'm in!</button> </div> <div class="col-md-4 col-sm-4"> <button type="submit" class="btn btn-default btn-block" value="False" id="subButton" name="is_attending" onclick="FbotonOf()">Sorry, i can't!</button> </div> And this jQuery: $('#post-form').on('submit', function(e) { e.preventDefault(); $("#subButton").click(function(e){ e.preventDefault(); var my_button = $(this).val(); $.ajax({ type : "POST", url: "{% url 'guest_update' %}", data: { guest_id : "{{ guest.guest_id }}", invites_names : $('#name').val(), phone_no : $('#phone').val(), best_wishes : $('#wishes').val(), with_partner : $('#myCheck:checked').val(), partner_name : $('#partner_name').val(), is_attending : my_button, csrfmiddlewaretoken: '{{ csrf_token }}', dataType: "json", }, success: function(data){ $('output').html(data.msg) }, failure: function() { } }); }); }); Every time I try to submit a form and press the first button, it works, but the second one, it doesn't. I've tried also without the click function but if a press the second button, I receive the first one value. Where am I wrong? -
how to use 2dicts in a for loop in Django template?
I have context as below : context = { 'author': author, 'books':books, } Now I need to use author and books in One for loop like this : {% for each in ***author & books*** %} <tr> <td>{{ each.author.name }}</td> <td>{{ each.book.name }}</td> <td>{{ each.book.pubishDate }}</td> </tr> {% endfor %} How to make such a for loop in Django template? Thanks all. -
Django: Starting explicit transaction while creating/saving objects
I've got a Django application, which has an form to order stuff. When the form is submitted, I am creating a new user and new order. The username should be the same as the order pk/id (which has an auto-increment) and 1:1 relation between user and order is required by business. And this brings me to my problem: Model looks like this (simplified). User is from django.contrib.auth.models class Order(models.Model): user = models.OneToOneField(User) comment = models.TextField order_status = models.CharField price = models.DecimalField(..) In order to get this id/pk of the order, I need to create and save it. But as a User is required, I need to create and save it even before the order is created. According to the documentation of Django, it creates transactions automatically. Instead I would like to open it by myself then fetch the next ID for the order and then create and save user and order. Is this the right way to do? And how would I accomplish this with Django? I am fairly new to Django and asking for advice. Thanks! -
Not Found: /addTodoItem/
i work on todo project and have a error. my models :: class TodoList(models.Model): content = models.TextField() my urls :: urlpatterns = [ path('', views.TodoappView , name = "todoappview"), path('', views.addTodoItem, name = 'Add Todo Item'), path('todoapp/<int:i>/', views.deleteTodoView, name = 'deleteTodoView') ] and my views:: def TodoappView(request): all_todo_items = models.TodoList.objects.all() return render(request, 'todoapp/todolist.html', {'all_items':all_todo_items}) def addTodoItem(request): x = request.post['content'] new_item = models.TodoList(content = x) new_item.save() return HttpResponseRedirect('/todoapp/') def deleteTodoView(request, i): y = models.TodoList.objects.get(id= i) y.delete() return HttpResponseRedirect('/todoapp/') and i have this error :: (Not Found: /addTodoItem/) Can anyone help me ????!!!!!!!!! -
How to control whether an object is related to a model or not in Django?
There are several models that are related to User model: class User(AbstractUser): # Its fields class Model_1(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields class Model_2(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields class Model_3(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields class Model_4(models.Model) user = models.OneToOneField('User', on_delete=models.CASCADE) # other fields and in the view: def index(request): # If the user is related to model one, do something # If the user is related to model two, do something # If the user is related to model three, do something # If the user is related to model four, do something # Otherwise return to the home page After the user sends the request to View, how do I determine which of these models it belongs to? Thank you in advance. -
Getting "page not found" error while trying to go back to the previous page after successful deletion using DeleteView in django
So I'm deleting an object of a model using DeleteView and redirecting to homePage after successful deletion, works fine. But the problem is when I try to get back to the previous page after deletion(using the left arrow button in the browser). I get "page not found" error which makes total sense because I'm trying to get back to the deletion page of an object which no longer exist. How do I prevent this from happening? -
Django: Sending e-mails asynchronous
I've got a Django application, which has an form to order stuff. After the form is submitted you should be forwarded to a confirmation site, while two e-mails should be send as well. Sending an e-mail with Django is not the problem send_mail(subject, plain_message, from_email, [order.customer.email], html_message=html_message) but it seems not happening in a asynchronous way as it takes some time. I would just like call my send_email method, let the sending be handled asynchronous and then proceed with forwarding. How would I accomplish this, what kind of possibilities do I have? I am fairly new to Django/Python but I imagine creating a Thread or sth like it? Whats best practise for this case? -
Django - pre_delete signal not updating instance's foreign key
I am trying to use a pre_delete signal for a Like model. Inside the signal handler, I try to update the num_of_likes field of one of Like's foreign keys, Book. My problem is that changes to a_book.num_of_likes inside my pre_delete signal handler do not reflect outside pre_delete. My code will make what the problem is very clear, I think (please pay special attention to the comments and print statements): books/models.py: class Book(models.Model): num_of_likes = models.IntegerField() likes/models.py: class Like(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) likes/views.py: class DeleteLikeView(APIView): def post(self, request, book): book = get_object_or_404(Book, id=book) print(book.num_of_likes) # Prints, say, 10 like = Like.objects.get(user=request.user, book=book) like.delete() # triggers signal handler below (should update `book.num_of_likes`) print(book.num_of_likes) # Still prints 10, expected 9 <------ PROBLEM return ... likes/signals.py: @receiver(pre_delete, sender=Like) def delete_book_like(sender, instance, **kwargs): print(instance.book.num_of_likes) # Prints 10 instance.book.num_of_likes -= 1 instance.book.save() print(instance.book.num_of_likes) # Prints 9, as expected Why does book.num_of_likes get updated inside delete_book_like but then changes don't show up in DeleteLikeView? -
Queryset to max value for group
I'd like to select the row with the max value, group them by line_nm and get the fields of this lines. In My models.py I have the follow fields: class SmdDropRateCe(models.Model): sumr_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) shift_code = models.CharField(max_length=10, blank=True, null=True) model_code = models.CharField(max_length=30, blank=True, null=True) equip_id = models.CharField(max_length=30, blank=True, null=True) mat_code = models.CharField(max_length=30, blank=True, null=True) reel_no = models.CharField(max_length=10, blank=True, null=True) err_num = models.IntegerField(blank=True, null=True) pckp_num = models.IntegerField(blank=True, null=True) plac_num = models.IntegerField(blank=True, null=True) err_ppm = models.FloatField(blank=True, null=True) I'd like to group then by model_code and recovery the data from the rows with the max err_ppm fields Example: recovery the fields: line_nm , equip_id , reel_no err_ppm I tried the follow: dropWorst1 = dropToday.values('line_nm').annotate(worst1=Max('err_ppm')).order_by('line_nm') However it only returns the fields: line_nm, worst1 I also tried: dropWorst1 = dropToday.order_by('-err_ppm','line_nm').distinct('line_nm') But it returns error: DISTINCT ON fields is not supported by this database backend Because I'm using mysql Someone knows how to fix this issue, I already look for many different solutions, without success. Tks in advance