Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass error logging parameters in python django as a wrapper function and use it for every method?
I am using Django-DB-logger for capturing my error logs in every method.I have multiple logging parameters----> user, class_name, method_name, module_name, ip_address, process_time. I need to get logs from every method. Given below is a sample method where I used my logging parameters. import logging import sys import socket import time from django.shortcuts import render from django.urls import resolve from rest_framework import status, request from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView class Request(APIView): @api_view(['GET']) def test_api_method(self): startTime = time.time() print('This is Test API') db_logger = logging.getLogger('db') try: 1 / 0 except Exception as e: endTime = time.time() db_logger.exception(e, extra={'user': self.user.username, 'class_name': self.__class__.__name__, 'method_name': sys._getframe().f_code.co_name, 'module_name': __package__, 'ip_address': socket.gethostbyname(socket.gethostname()) 'process_time': endTime - startTime}) return Response({'data': True}, status=status.HTTP_200_OK) Rather than using all the parameters in every method like above, I want to use to decorator/ wrapper class (in a separate .py file) so that I can just call that decorator every time for capturing parameters during exception handling in all the methods in different .py files. Kindly reply soon. -
POST method does not pass the value password from the input field
Here form is submitted via POST method but password given in the input field of type=password not assigning to 'upassword' given in the userregister function.When I print the 'upassword' it gives an output "None".Also it gives an error like this when I give JAVASCRIPT validation. Internal Server Error: /Salon/Registration/ Traceback (most recent call last): File "C:\PYTHON\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\PYTHON\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\salon\user\views.py", line 53, in salonregister epassword = sha256(spassword.encode()).hexdigest() AttributeError: 'NoneType' object has no attribute 'encode' HTML file: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>Registration</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="{% static 'styles/style.css' %}" rel="stylesheet"/> <script src="jquery-3.5.1.min.js"></script> </head> <body> <section class="sreg" id="sreg"> <div class="container-fluid"> <div class="htop"> <h4>Register Form</h4> </div> <div class="row"> <div class="col-12"> <form method="POST" name="contact" action="{%url 'salonregister' %}"> {%csrf_token%} <div class="form-row"> <div class="form-group col-md-6"> <label for="fname">First Name</label> <input type="text" class="form-control" id="fname" name="fname" placeholder="First Name"> <span id="lfname"></span> </div> <div class="form-group col-md-6"> <label for="lname">Last Name</label> <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name"> <span id="llname"></span> </div> </div> <div class="form-group"> <label for="email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="Email"> <span id="lemail"></span> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" name="pass" placeholder="Password"> <span id="lpass"></span> … -
400 bad request during axios call
Not sure why but the POST request is coming back 400. Postman says my django backend is doing fine. It all happens at the post_flashcards method any help would be great and I am willing to show any other code as requested. although there shouldnt be the need to since this component acts mostly on its own. class CreateFlashCard extends Component { constructor(props) { super(props); this.state = { title: '', collection_id: '', term: '', definition: '', } this.handleSubmit = this.handleSubmit.bind(this) } onChange = (e) => { this.setState({[e.target.name]: e.target.value}); } handleSubmit(e) { e.preventDefault(); this.post_flashcard() } async post_flashcard() { const card = this.state; const col_id = parseInt(this.state.collection_id) try{ await axios.post(`http://127.0.0.1:8000/flashcardsapp/${col_id}`, card) .then(response => console.log(response.status)) }catch(er){ console.log('ERROR in post_flashcard', er) } } render() { const {title, collection_id, term, definition} = this.state return ( <form onSubmit={this.handleSubmit}> <h2>Create a Card</h2> <label for="title">Enter Collection Title</label> <input type="text" name="title" value={title} onChange={this.onChange} ></input> <label for="collection_id">Enter Collection ID</label> <input type="number" name="collection_id" value={collection_id} onChange={this.onChange} ></input> <label for="term">Enter Term</label> <input type="text" name="term" value={term} onChange={this.onChange} ></input> <label for="definition">Enter Definition</label> <input type="text" name="definition" value={definition} onChange={this.onChange} ></input> <input type="submit"></input> </form> ); } } export default CreateFlashCard; -
How to order related objects at first?
Here I want to show navs which are in the role already at first then show remaining navs. models class MyGroup(models.Model): name = models.CharField(max_length=100) navs = models.ManyToManyField('Nav', blank=True, related_name='navss') class Nav(models.Model): name = models.CharField(max_length=200) views class GroupDetailView(View): template = 'group_detail.html' def get(self, request, *args, **kwargs): group = MyGroup.objects.get(pk=kwargs['group_id']) group_navs = group.navs.all() # display this first navs = Nav.objects.exxclude(pk__in=group_navs) #then display this inside template -
TypeError at /api/questions/ 'list' object is not callable (Django)
When I go to this http://127.0.0.1:8000/api/questions/ I get TypeError at /api/questions/ 'list' object is not callable urls.py (in project) """QuestionTime URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path, re_path from django_registration.backends.one_step.views import RegistrationView from core.views import IndexTemplateView from users.forms import CustomUserForm # https://django-registration.readthedocs.io/en/3.1.2/activation-workflow.html urlpatterns = [ path('admin/', admin.site.urls), path("accounts/register/", RegistrationView.as_view( form_class=CustomUserForm, success_url="/", ), name="django_registration_register"), path("accounts/", include("django_registration.backends.one_step.urls")), path("accounts/", include("django.contrib.auth.urls")), path("api/", include("users.api.urls")), path("api/", include("questions.api.urls")), path("api-auth/", include("rest_framework.urls")), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")), re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point"), ] urls.py (in appName/api from django.urls import include, path from rest_framework import urlpatterns from rest_framework.routers import DefaultRouter from questions.api import views as qv router = DefaultRouter() router.register(r"questions", qv.QuestionViewSet) urlpatterns = [ path("", include(router.urls)), path("questions/<slug:slug>/answers/", qv.AnswerListAPIView.as_view(), name="answer-list"), path("questions/<slug:slug>/answer/", qv.AnswerCreateAPIView.as_view(), name="answer-create"), path("answers/<int:pk>/", qv.AnswerRUDAPIView.as_view(), name="answer-detail"), path("answers/<int:pk>/like/", qv.AnswerLikeAPIView.as_view(), name="answer-like"), ] Error could come from somewhere else. … -
Duplicate in Object storage
I use a Minio-backend in the Django app. I have a feature that users can use the object storage(user online gallery), and Also, users can upload a new image from the device to create a post. But when I use the object storage images and create an image, images duplicate in object storage(because each time I create a post, I want to upload new images( images that upload locally) in object storage). What should I do to prevent these duplicates? It is my model: class MediaStorage(models.Model): file = models.FileField(verbose_name="Object Upload", storage=MinioBackend(bucket_name='django-backend-dev-private'), upload_to=iso_date_prefix) this is my create new post : class CreatePostView(generics.CreateAPIView): ... def post(self, request, *args, **kwargs): user = request.user data = request.data ... for media_file in post_files: file_team=post_team f = MediaStorage.objects.create(team=file_team,owner=user) f.media=media_file f.save() post.multimedia.add(f) return Response(post_serializer.PostSerializer(post).data, status=status.HTTP_201_CREATED) Thank you so much. -
DRF Updating model's CharFiled with choices doesn't do anything
I have a Task app in my django project. So this is the base class for the task model: TASK_STATUSES = [ ("DN", "Done"), ("IP", "In progress"), ("IR", "In review"), ("NW", "New"), ("RJ", "Rejected"), ("TD", "To do"), ] class TaskBase(models.Model): STATUS_CHOICES = TASK_STATUSES status = models.CharField("State", max_length=2, default="NW", choices=STATUS_CHOICES) [...] class Meta: abstract = True This is the actual model: class Task(TaskBase): TYPE_CHOICES = TASK_TYPES type = models.CharField("Type", max_length=1, default="T", choices=TYPE_CHOICES) project = models.ForeignKey(Project, on_delete=models.CASCADE) Serializer: class TaskSerializer(serializers.ModelSerializer): status = serializers.CharField(source="get_status_display") class Meta: model = Task fields = "__all__" And the viewset: class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer lookup_field = "name" permission_classes = [] authentication_classes = [] Now I update the task's status via PATCH request to /api/task/<task_name>/ with {"status": "TD"}. So the response is "PATCH /api/task/XYZ/ HTTP/1.1" 200 233 - everything is fine, I receive "TD" in the response data - the status changed. But when I get the task again, it still has his previous status ("New"). So I see two problems: I change the status, 201 HTTP response, the response from api contains changed status - but it does not change in my DB The status that I receive in response is not in "To … -
Supervisor spinning up multiple celery and worker processes on aws
I am running the setup that follows(just showing the beat setup for simplicity) for daemonizing my celery and beat workers on Elastic beanstalk. I am able daemonize the processes successfully however too many processes are being spawned. I have attempted adding a container command that kills all processes with celery in its name which gives in an attempt to automate this process but not all processes were killed. Current Output root 20409 0.7 9.1 473560 92452 ? S 02:59 0:01 /opt/python/run/venv/bin/python3.6 /opt/python/run/venv/bin/celery -A djangoApp worker --loglevel=INFO root 20412 0.6 7.8 388152 79228 ? S 02:59 0:01 /opt/python/run/venv/bin/python3.6 /opt/python/run/venv/bin/celery -A djangoApp beat --loglevel=INFO root 20509 0.0 7.1 388748 72412 ? S 02:59 0:00 /opt/python/run/venv/bin/python3.6 /opt/python/run/venv/bin/celery -A djangoApp worker --loglevel=INFO root 20585 0.6 7.7 387624 78340 ? S 03:00 0:01 /opt/python/run/venv/bin/python3.6 /opt/python/run/venv/bin/celery -A djangoApp beat --loglevel=INFO root 20679 1.1 9.1 473560 92584 ? S 03:01 0:01 /opt/python/run/venv/bin/python3.6 /opt/python/run/venv/bin/celery -A djangoApp worker --loglevel=INFO root 20685 0.0 7.1 388768 72460 ? S 03:01 0:00 /opt/python/run/venv/bin/python3.6 /opt/python/run/venv/bin/celery -A djangoApp worker --loglevel=INFO Desired output as achieved by after the environment deploys running kill -9 $(pgrep celery) root 20794 20.6 7.7 387624 78276 ? S 03:03 0:01 /opt/python/run/venv/bin/python3.6 /opt/python/run/venv/bin/celery -A djangoApp beat --loglevel=INFO root 20797 24.3 9.1 … -
Overriding the save method for all the models in Django
I want to override the save method for all the models in my application. It can be easily done by using inheritance class MyModel(models.Model): def save(*args, **kwargs): # Do something here... super().save(args, kwargs) class User(MyModel): .... The problem with this approach is that this will need a change in the already defined models. Also, models defined in the external libraries will also need to be taken care of separately. Is there a better way to do it? -
Database Locked error while creating super user
python manage.py createsuperuser This error shown after password input Traceback (most recent call last): File "C:\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: database is locked how to resolve -
About the use of django-import-export
Our project uses DRF+vue, and the data export uses django-import-export. The current demand is that the front-end transfers the specified fields, and the back-end needs to export these data to excel according to this specified field. I have already got the front-end in the views. The specified fields passed, how to go to resources to dynamically add fields to fields and export these data. views.py enter image description here resources.py enter image description here -
Error: relative import with no known parent package
[Newbie] Good evening, I'm a newbie using python I just created a project in Django and I want to save a basic record as the first and last name of an employee. I created a "seed.py" file within my "employee" application that should create a new record in the database with the employee's first and last name. I'm instantiating my "Seed" object inside "manage.py" which would be the main class, every time I start my application, the seed.py code has to be executed, but it gives me an error when trying to execute the code. "An exception occurred: ImportError relative import attempt without a known parent package File "C: \ GitHub \ django \ backend \ api \ manage.py", line 5, in from .employee.seed import Seed django project (folder) C: \ GitHub \ django \ backend \ api \ django app (folder) C: \ GitHub \ django \ backend \ api \ employee What am I doing wrong? c:\GitHub\django\backend\api\manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from .employee.seed import Seed def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's … -
Image not saving in database(mysql) and displaying null as blob in django
I am saving 4 images from the user (maybe it will be null). I do not want to save the images in a directory or folder,I need to save the images in db(mysql). The 'form.save' is working and after looking in db the blob is present but there is no data in it.Not only that the null is displaying as blob! forms.py class ClientCreateForm(ModelForm): photo = forms.ImageField(required=False) signature = forms.ImageField(required=False) poi_image = forms.ImageField(required=False) poa_image = forms.ImageField(required=False) model.py class Client(models.Model): photo = models.ImageField(db_column='PHOTO', blank=True, null=True) signature = models.ImageField(db_column='SIGNATURE', blank=True, null=True) poi_image = models.ImageField(db_column='POI_IMAGE', blank=True, null=True) poa_image = models.ImageField(db_column='POA_IMAGE', blank=True, null=True) views.py def client_create_view(request): if request.method == 'POST': form = ClientCreateForm(request.POST) if form.is_valid(): form.save else: pass -
Twitter/Reddit posts not embedding properly on Django template
I'm building a news aggregator. I am connected to the twitter and reddit APIs through the tweepy and PRAW libraries. I'm pulling json data from twitter and reddit, and displaying posts in a timeline format side by side. I have one template called main.html which takes in context(reddit post ids; twitter status urls) and passes that context to template tags, in order to generate html to embed. Here is the template where all this work is being done. The template tags are 'tweet_tags.py' and 'red_attempt.py' as you can see loaded at the top of the page. {% block content %}{% load red_attempt %} {% load tweet_tags %} {% autoescape off %} <h1>Welcome</h1> <a href="/main" class="btn btn-danger">Refresh News</a> <div class="container"> <div class="row"> <div class="col-6"> <h3 class='text-center'>Reddit News</h3> {% for item in reddit %} <div class="mdl-card__media" id="timeline"></div> {% red_attempt item %} <br> {% endfor %} </div> <div class="col-6"> <h3 class='text-center'>Twitter News</h3> {% for item in twitter %} <div class="mdl-card__media" id="timeline"></div> {% tweet_tags item %} <br> {% endfor %} </div> </div> </div> {% endautoescape %}{% endblock %} The template tags are 'tweet_tags.py' and 'red_attempt.py' as you can see loaded at the top of the page. Here is their code, respectively: tweet_tags.py def tweet_tags(url): … -
How to remove old form to stop double-submission
I am using AJAX to submit a form from a modal window. If the form is submitted with errors the server will send back a new form. The container holding the old form is then removed and the new form, with validation errors, is set in it's place. The issue is that, for some reason, it submits 2 forms at the same exact time after the validation errors are fixed. It is as-if the old form does not get removed? It does not happen when I use the onclick=functionCall() syntax but rather when I use the $('form').on('submit', e => { syntax. I am trying to use the latter as I was told the onX events are now considered bad practice. Any help on understanding what is happening and how to fix it would be useful. Form: // Submit Form $('form').on('submit', e => { e.preventDefault(); let data = new FormData($(e.target).get(0)); const btn = $(e.target).find('button:submit') const container = document.getElementById('formFields') $.ajax({ url : e.target.action, data : data, type : 'POST', headers : {"X-CSRFToken": token}, enctype : 'multipart/form-data', processData : false, contentType : false, success : function (data) { btn.toggleClass('btn-warning btn-secondary').prop('disabled', true) }, error : function (data) { container.innerHTML = loadingSpinner; $(container).empty(); $(container).html(data['responseJSON']['table']).fadeIn('slow'); }, … -
Django's SECRET_KEY for Two Computers
I am new to Django(3.2) and learning from Django Website's tutorial using two computers. Recently I learned how to use python.decouple module and .env to keep SECRET_KEY locally. But the thing is that I am using two computers and github to work on a project. So each computers are currently holding locally different SECRET_KEY. For now, pulling and pushing works, but this made me think about what might cause problem if I keep developing this project in this way. So I found this post, but it is about the project on service. I tried to search on stack overflow and google, but I found no similar situation as mine. (Does this indicate that I should the same SECRET_KEY? But why?) Since this question might sound too broad, to narrow it down a bit, I would say that my question is 'Will using two different SECRET_KEY's for a project cause problem? What are some problems with most impact?' Thank you in advance for your help. -
Mostrar en el template de django solo los articulos cuyos nombres guardados a traves de mi modelo empiecen con una letra especifica designada
Quisiera saber como podria mostrar en mi template solo los articulos que su nombre empiece con una letra determinada. Por ejemplo: en models.py tengo: class Juego(models.Model): id = models.AutoField(primary_key =True) nombre = models.CharField(max_length=300) def __str__(self): return self.nombre Ahora en views.py tengo def catalogo(request): juegos = Juego.objects.all() print(juegos) contexto = {'juegos':juegos} return render(request,'catalogo.html',contexto) y lo que quisera es que alguien pudiera ayudarme a ver si puede haber algun metodo de hacer algo asi en el template, o mejor desde una funcion realizada {% if{{juegos.nombre}} == "A" or "a" %} <p>{{juegos.nombre}}<p> {% end if%} de esta manera todos los juegos guarde no importa con que nombre en este template solo se mostraran solo los que empiecen con la letra A. Eso es lo que quiero hacer. Saludos a todos -
Render Django and React views in the same app
we currently have the entire front-end in Django. All the html tags are in Django templates and we want to migrate a part of the application to React (in a different server), so how can we do this? I think we can redirect from Django the view path in React, but I don't know how to do it. Any ideas ? Thanks! -
Formsets for class based views (CreateView and UpdateView
I am adding formsets for my clientcreateview and clientupdateview. I've been watching tutorials but it's mostly dependent to def based. I would likt to know how to implement it for class based views. Please help me. Thank you very much in advanced. here's my models.py: class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField(null=True, blank=True) position = models.CharField(max_length=30, default=None) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=6, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return self.company_name class Branches(models.Model): client = models.ForeignKey("Client", related_name="+", blank=True, null=True, on_delete=models.SET_NULL) branches_quantity = models.IntegerField(default=1, blank=True, null=True) baranggay = models.CharField(max_length=50) city = models.CharField(max_length=50) region = models.CharField(max_length=50) def __str__(self): return self.client class Meta: db_table = "branches" class ContactPerson(models.Model): client = models.ForeignKey("Client", related_name="+", blank=True, null=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) position = models.CharField(max_length=30) mobile_number = models.CharField(max_length=12) email = models.EmailField(null=True, blank=True) def __str__(self): return self.client class Meta: db_table = "contact_person" class ClientUpdateView(OrganizerAndLoginRequiredMixin, generic.UpdateView): template_name = "clients/client_update.html" form_class = client_ModelForm_Organizer … -
Hash a password field outside of the User model - Django
I am trying to have a user register, and then log in. Once they are logged in they specify their WiFi name, followed by a wifi password, and their choice of a VPN. The problem I am having is hashing the wifi_password field upon saving it to the database. I am trying to hash the password within the edit function in views.py. I have posted the entirety of my models, forms, and views. The code is still sloppy, and will need some cleaning up when I can achieve functionality. Thanks. models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings vpn_choices = [ ('openvpn', 'Open VPN'), ('pia', 'Private Internet Access'), ('expressvpn', 'Express VPN'), ] class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True) wifi = models.CharField(max_length = 128) wifi_password = models.CharField(max_length = 128) vpn_choice = models.CharField(max_length = 20, choices = vpn_choices) def __str__(self): return f'self.user.username {self.user.username}' forms.py from django import forms from django.contrib.auth.models import User, AbstractUser from django.contrib.auth import get_user_model from server.models import Profile from django.forms import ModelForm vpn_choices = [ ('openvpn', 'Open VPN'), ('pia', 'Private Internet Access'), ('expressvpn', 'Express VPN'), ] class LoginForm(forms.Form): username = forms.CharField(max_length = 126) password = forms.CharField(max_length = 126, widget … -
NoReverseMatch at /contact/ Reverse for 'contact_result' not found. 'contact_result' is not a valid view function or pattern name
I am trying to make a contact form, but I guess I'm doing it wrong. When I access /contact and put name, email, content in each field and click a submit button, I got an error. NoReverseMatch at /contact/ Reverse for 'contact_result' not found. 'contact_result' is not a valid view function or pattern name. view.py from django.urls import reverse_lazy from django.views.generic import TemplateView from django.views.generic.edit import FormView from .forms import ContactForm class ContactFormView(FormView): template_name = 'contact/contact_form.html' form_class = ContactForm success_url = reverse_lazy('contact_result') def form_valid(self, form): form.send_email() return super().form_valid(form) class ContactResultView(TemplateView): template_name = 'contact/contact_result.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['success'] = "completed" return context urls.py from . import views from .views import DbDetail,ContactFormView, ContactResultView app_name = 'db' urlpatterns = [ path('', views.DbList.as_view(), name='list'), path('contact/', ContactFormView.as_view(), name='contact_form'), path('contact/result/', ContactResultView.as_view(), name='contact_result'), ] contact_form.html {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> <h1>inquily</h1> <p>inquily form</p> <form method="POST">{% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">submit</button> </form> </div> </div> </div> {% endblock %} contact_result.html {% block content %} {{ success }} {% endblock %} I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank … -
How to define fieldsets in ModelForm?
I am trying to create a custom form for User model, I tried from django.contrib.auth.forms import UserChangeForm class CustomUserForm(UserChangeForm): class Meta: model = User fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ( 'first_name', 'last_name', 'email' )}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) but Django complains and requires fields or exclude to be defined in forms' meta. -
Comparing Dates in Django
I need to compare a date field in my bookings table with today's date. I am trying to loop through all bookings dates and if the date is less than today's date date to change a field status to "Completed" I keep getting the below error "TypeError: '<' not supported between instances of 'datetime.date' and 'str'" I have tried to research this but I am unable to resolve the issue. Below is my code. Model.(ASPBookings) booking_date = models.DateField() View date_today = (datetime.datetime.now()) date_stripped = date_today.strftime('%Y-%m-%d') asp_date_data = ASPBookings.objects.all() for booking in asp_date_data: print (booking.booking_date) if booking.booking_date < date_stripped: booking.status == 'Completed' booking.save() I have checked the output of the fields and after stripping the time the dates appear the same. eg. ASPBookings field dates 2021-05-27 2021-06-24 2021-06-15 Today's date 2021-06-09 Thanks in advance for any help I can get on this. -
Conditionally Access and Direct User in Django Class-Based View
I have a Django custom form classed-based view. Under normal conditions I want it to be accessible to both authenticated and logged out or anonymous visitors. However, under certain conditions I'd like it to alert the user they need to login to submit the form (and redirect them). Example: class CustomFormView(FormView): ... def form_valid(self, form): user = self.request.user req_id = self.request.GET.get("req_id") if req_id: errors = False if not user.is_authenticated(): messages.error(self.request, "You must be logged in to fill out this form. Please sign in, then visit this link again.") errors = True # redirect try: ... if errors: ctx = self.get_context_data() return self.render_to_response(ctx) I'm aware of LoginRequiredMixin (docs) as well as a decorator @method_decorator(login_required) but I don't want to apply it at the view level or to the entire form_valid() function, only check login state when if req_id condition is met. Currently the view's not executing my if not user.is_authenticated(): so my attempt isn't correct. Is there a way to accomplish this within form_valid()? thanks -
Django QuerySet .count() is 0 and .exists() is false, even though there's an object in the QuerySet (Django Rest Framework)
I've had an intermittent bug for months and I am stuck! Help is appreciated. @receiver(models.signals.post_delete, sender=ContentFile) def delete_file(sender, instance, *args, **kwargs): class ContentFile(models.Model): """ Represents the metadata for a single document. """ name = models.CharField(max_length=200) set = models.ForeignKey(Set, related_name='contentfile_set', on_delete=models.CASCADE) location = models.FileField(upload_to=get_content_file_upload_path) class Meta: app_label = 'ProtocolManager' unique_together = ('set', 'location') def __str__(self): return f"File {self.name} at location {str(self.location)} attached to {self.set}" """ Delete orphaned file once last ContentFile is removed. """ log.info(f"Checking {instance.location} for existing ContentFile") if instance.location: from django.db import connection from django.db import reset_queries reset_queries() files_queryset = ContentFile.objects.filter(location=instance.location) if not files_queryset.exists(): log.info(f"ContentFile does not exist for {instance.location}, deleting...") log.info(f"SQL: {connection.queries}") log.info(f"files_queryset: {list(files_queryset.all())}") log.info(f"count: {files_queryset.count()}") log.info(f"exists: {files_queryset.exists()}") instance.location.delete(save=False) The logic is pretty simple. When a ContentFile row is deleted, if it was the last one referring to an actual file location, we delete the file itself (on AWS S3, if it matters). 99% of the time this works as expected, but sometimes it will fail, and when it fails, it seems to fail for all of the ContentFiles associated with a given Set. I added the verbose logging to try to get more clues, but today it finally reproduced for the first time in months and the …