Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django wont import pages app to urls file
While I was following this tutorial https://www.youtube.com/watch?v=F5mRW0jo-U4&t=3838s I was trying to customize the home page of my django project by creating a new project called pages by doing python manage.py startapp pages the only edit I made to this app was in the view.py file by doing this But whenever I try to reference this file in the urls.py file in the trdjango folder it gives me an import error like this This is really frustrating because I am new to this web framework and I was following the tutorial exactly and yet I still get this error Does anyone know why it isn't recognizing the import or how I would fix this? -
Django - don't post that specific form if left blank
I am building on the learning django tutorial (relatively new to both python and django), with a page where a user can create a question and some optional polls for users to vote on. I have a standard 4 options for choices, right now they are each a separate 'form' that will submit that choice to the question. Only issue is I would like to make it so if that specific one is left blank, the others will be submitted but that one will not. Right now when I try and leave it blank it says it is a required field and I am unable to submit. Is there any way around this? I have tried to change put before validation that the field is not required, but since I cannot submit, it does not hit that logic. The way the form is laid out right now has multiple forms inside, one for the question and 4 for choices, and all are wrapped within one form in the html. -
ImportError: No module named social_django.middleware.in import_module __import__(name)
Hello I am trying to execute a project that is made in django 1.10.8 and pyhon 2.7 and the python_social_auth library. When I try to execute the project I get the following error.I hope you can help me manage.py runserver Unhandled exception in thread started by <function wrapper at 0x7f4b908eb488> Traceback (most recent call last): File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 39, in inner_run http_consumer=self.get_consumer(*args, **options), File "/home/mauricio/.local/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 134, in get_consumer return StaticFilesConsumer() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 327, in __init__ self.handler = self.handler_class() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/staticfiles.py", line 18, in __init__ super(StaticFilesHandler, self).__init__() File "/home/mauricio/.local/lib/python2.7/site-packages/channels/handler.py", line 177, in __init__ self.load_middleware() File "/home/mauricio/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/home/mauricio/.local/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named social_django.middleware -
Django-filter fields to select
my code: import django_filters from django_filters.views import FilterView User = get_user_model() class supplierFilter(django_filters.FilterSet): class Meta: model = Supplier fields = ['supplier_name', ] class SupplierFilterList(FilterView): template_name = "supplier/Supplier_list.html" model = Supplier context_object_name = 'supplier' filter_class = supplierFilter def get_queryset(self): organisation = self.request.user.userprofile.company return Supplier.objects.filter(organisation=organisation) my template: <form action="" method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> I just want to have a filter on name but my template looks like this: So I have all fields of my model and not only name -
Environment Variables Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
During the last couple days I have been trying to use environment variables in django but it just seems impossible. I made my .env file and put it in my project directory with all the variables. When I run the server it says that my secret key is not defined even though I am loading my environment variables. I do not know what I am doing wrong in this project because this approach work just fine in another one i made. If someone can find the error I would really appreciate it a lot. settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import django_heroku from pathlib import Path import os import dj_database_url import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent dotenv_file = os.path.join(BASE_DIR, "env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True … -
Joining multiple models in order to get an orm query in Django?
I have to return the average length of the most sold tracks in a certain time, using 3 models i manage to form an sql query that looks something like this select *, AVG(m.milliseconds) as lengthTrack from InvoiceItem as il join invoices as i on i.invoiceid = il.invoiceid join track as t on t.trackid = il.trackid where i.invoicedate between '2012-01-01' and '2013-12-31' order by lengthTrack I manage to come up with this as I got really confused about how to join both tables in order to get the average length track of the 10 most sold ones : start_date = datetime.date(2012, 01, 01) end_date=datetime.date(2013, 12, 31) InvoiceItem .objects.filter(ino_date__range=(start_date, end_date),) in the views do i need to add the 3 serializers in erializer_class? i also wanna ask if my query right ? -
Cant complete a complex query in Django
I have this two tables: class HotelInfo(models.Model): country_area = models.CharField(max_length=45) hotel_id = models.CharField(primary_key=True, max_length=32) hotel_name = models.TextField(blank=True, null=True) hotel_url = models.TextField(blank=True, null=True) hotel_address = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) review_qty = models.IntegerField(blank=True, null=True) clean = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) comf = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) loct = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) fclt = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) staff = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) vfm = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) wifi = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'hotel_info' unique_together = (('hotel_id', 'country_area'),) verbose_name_plural = "hotels" class HotelReviews(models.Model): uuid = models.CharField(primary_key=True, db_column='UUID', max_length=36, blank=True) hotel = models.ForeignKey(HotelInfo, on_delete=models.DO_NOTHING) review_title = models.TextField(blank=True, null=True) review_url = models.TextField(blank=True, null=True) review_score = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) review_date = models.DateField(blank=True, null=True) reviewer_name = models.TextField(blank=True, null=True) hash_reviewer_name = models.CharField(max_length=200, blank=True, null=True) reviewer_location = models.CharField(max_length=100, blank=True, null=True) posting_conts = models.IntegerField(blank=True, null=True) positive_content = models.TextField(blank=True, null=True) negative_content = models.TextField(blank=True, null=True) tag_n1 = models.TextField(blank=True, null=True) tag_n2 = models.TextField(blank=True, null=True) tag_n3 = models.TextField(blank=True, null=True) tag_n4 = models.TextField(blank=True, null=True) tag_n5 = models.TextField(blank=True, null=True) staydate = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'hotel_reviews' verbose_name_plural = "Reviews" And I want get the hotels with more than 5 reviews_qty in 2019 and then get … -
How to use Django form-wizard on a model using ModelForms?
How to use django-formtools Form wizard on a model using ModelForms? My forms are rendering but the data is not being saved for some reason, and the form is therefore invalid so never reaches done method. I've never used Form wizard before and finding it hard to find much in terms of documentation or tutorials. models.py [abbreviated for simplicity] class Applicant(models.Model): first_name = models.CharField(max_length=150, null=False, blank=False) last_name = models.CharField(max_length=150, null=False, blank=False) phone = models.CharField(validators=[phone_regex], max_length=60, null=True, blank=True) email = models.EmailField(blank=False, null=True) .... forms.py [abbreviated for simplicity] class ApplicationStepOne(ModelForm): class Meta: model = Applicant fields = ('first_name', 'last_name', 'phone', 'email', ...,) class ApplicationStepTwo(ModelForm): class Meta: model = Applicant fields = ('age', ...,) class ApplicationStepThree(ModelForm): class Meta: model = Applicant fields = ('cats', 'dogs', ...,) class ApplicationStepFour(ModelForm): class Meta: model = Applicant fields = ('yard', ...,) views.py class FormWizardView(SessionWizardView): template_name = 'animals/application_form.html' model = Applicant form_list = [ApplicationStepOne, ApplicationStepTwo, ApplicationStepThree, ApplicationStepFour] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos')) success_url = reverse_lazy('animals:animals') def dispatch(self, request, *args, **kwargs): self.instance = Applicant() return super(FormWizardView, self).dispatch(request, *args, **kwargs) def get_form_instance( self, step ): if self.instance is None: self.instance = Applicant() return self.instance def done( self, form_list, **kwargs ): self.instance.save() for form in form_list: form.cleaned_data() return redirect(self.success_url) urls.py path('apptest/', FormWizardView.as_view([ApplicationStepOne, … -
Django wsgiref/handlers.py throws exception like always with python 3.9
I'm doing some django TDD samples following this article http://www.tdd-django-tutorial.com/tutorial/1/. But when I try to run my testing I always got this problem, $ ./manage.py runserver Performing system checks... System check identified no issues (0 silenced). March 12, 2021 - 16:58:38 Django version 2.1, using settings 'web_app.settings.develop' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [12/Mar/2021 16:58:40] "GET / HTTP/1.1" 200 1587 Traceback (most recent call last): File "c:\users\aleja\appdata\local\programs\python\python39\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 66, in __call__ return super().__call__(environ, start_response) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\core\handlers\wsgi.py", line 142, in __call__ response = self.get_response(request) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 58, in get_response return self.serve(request) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 51, in serve return serve(request, self.file_path(request.path), insecure=True) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\views.py", line 33, in serve absolute_path = finders.find(normalized_path) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\finders.py", line 263, in find result = finder.find(path, all=all) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\finders.py", line 98, in find matched_path = self.find_location(root, path, prefix) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\contrib\staticfiles\finders.py", line 115, in find_location path = safe_join(root, path) File "C:\Users\aleja\Documents\Projects\th-web-app\.venv\lib\site-packages\django\utils\_os.py", line 47, in safe_join raise SuspiciousFileOperation( django.core.exceptions.SuspiciousFileOperation: The joined path (C:\favicon.ico) is located outside of the base path component (C:\Users\aleja\Documents\Projects\th-web-app\static) [12/Mar/2021 16:58:41] "GET /static//favicon.ico HTTP/1.1" 500 59 [12/Mar/2021 16:58:43] "GET /static/develop/35e6fb86d66a830d45e377494420c11b.woff2 HTTP/1.1" 304 0 -
"no such column: id" Django AbstractUser model
I am trying to migrate, and view the admin page. both makemigrations and migrate passed, yet when i go to the admin url it reads this: "django.db.utils.OperationalError: no such column: social_app_user.id" And once i create an id field, it changes to "django.db.utils.OperationalError: no such column: social_app_user.password" I was under the impression that the AbstractUser model included all the default user fields, not sure about the primary key, but regardless. Please help, thanks! Note: the 'id' field in this models.py file was added after i got the error. from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class User(AbstractUser): is_verified = models.BooleanField(default=True) id= models.AutoField(primary_key=True, null=False) REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): f"{self.username} {self.email}" return class main_feed(models.Model): content= models.CharField(unique=True, max_length=255, default='', null=False) poster = models.ForeignKey('User', related_name='author', on_delete=models.CASCADE, to_field='username') likes = models.IntegerField(default=0, null=False) favorites = models.IntegerField(default=0, null=False) date_posted = models.DateTimeField(auto_now=True) def __str__(self): f"{self.content} {self.likes} {self.poster} {self.date_posted}" return -
How I'll fix it - NameError at /account/signup/ name 'SignUpForm' is not defined
I defined SignUpFrom but still, the server shows that name 'SignUpForm' is not defined by anyone, please suggest to me how I'll fix it. Thanks in advance. Code Location: App_Login Views.py views.py--App_Loginstrong text [from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import login, authenticate, logout from django.shortcuts import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required # Create your views here. def sign_up(request): form = SignUpForm() registered = False if request.method == 'POST': form = SignUpForm(data=request.POST) if form.is_valid(): form.save() registered = True dict = {'form':form, 'registered':registered} return render(request, 'App_Login/signup.html', context=dict) def login_page(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('index')) return render(request, 'App_Login/login.html', context={'form':form}) @login_required def logout_user(request): logout(request) return HttpResponseRedirect(reverse('index')) -
Django: database for admin purposes on local db.sqllight and app requests made on another database (PostgrSQL)
I am new to Django. I would like to have the admin part being managed by a local db.sqlight database and the app/web requests being made to another database (PostgreSQL). Do I need to create a Router class, in which folder (project or app). I went through the Django documentation/ tutorials but it was still unclear to me as of how to implement this. An example with directories/folders paths and settings.py values would be greatly apreaciated. Best Django3, Windowas, PyCharm community, PostgreSQL 12 -
Create object if doesn't exist when calling it by related_name
NOTE: I'm aware of get_or_create and it does not apply here. I have a Django app with a lot of users. One of my project apps must keep some kind of user preferences relating to this app, so in its' models.py I've created: [models.py] class UserPreferences(models.Model): user = models.ForeignKey( get_user_model(), related_name='adminpanel_preferences' ) ... (more boolean fields, integer choices etc) I don't want to use signals for creating a UserPreferences objects every time new user is being created. My idea was to only create an object when such object is somehow requested. This might sound like a perfect get_or_create use case, however I need to call this object from a template using the related_name e.g: [template.html] {% if request.user.adminpanel_preferences.hardcore_mode_enabled %} ... {% endif %} And while normally the request.user.adminpanel_preferences would return UserPreferences.None, I want it to silently create the object (using default field values) instead. Is there a possibility to achieve such behavior without interfering the User model? The UserPreferences are not global app preferences, they only refer to this particular app and I'd love to keep these two independent. I have also tried using a custom objects manager with customized get_queryset method but it doesn't seem to work when using … -
How do you delete all manytomany relationships in a model in form_valid?
I am making a booking system with Django. I want to be able to have a view to "cancel" bookings. This involves setting the participants (manytomany) of the model to None and the booked_by to none. I don't want to delete the booking as someone else might like to book it later instead. I suppose the ability to delete all relationships in manytomany for the BookingSlot would work. I would like to be able to do this in form_valid(). #views.py class CancelBookingView(UpdateView): form_class = CancelBookingForm model = BookingSlot def form_valid(self, form): form.instance.booked_by = None #This works fine form.instance.participants.all = None #This doesn't work return super().form_valid(form) So far as you can see what I have tried, it hasn't worked. Help would be much appreciated, thank you! #models.py class BookingSlot(models.Model): start_time = models.TimeField("Start Time") end_time = models.TimeField("End Time") date = models.DateField("Date") location = models.ForeignKey(Court, on_delete=models.CASCADE) booked_by = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, default=None, blank=True, null=True, related_name="bookedBy_CustomerUser") participants = models.ManyToManyField(CustomUser, default=None, blank=True, related_name="participant_CustomerUser") -
Integrity error handled and personalized message
I put a constraint like this: class Supplier(models.Model): supplier_name = models.CharField(max_length=100, null=False, blank=False) supplier_created_by = models.ForeignKey("users.User", on_delete=models.CASCADE, related_name='user') class Meta: constraints = [ models.UniqueConstraint(fields=['supplier_name', 'supplier_created_by'], name='Supplier unique in company') ] My views is: class supplierCreateView(LoginRequiredMixin, CreateView): template_name = "supplier/supplier_create.html" form_class = SupplierModelForm def get_success_url(self): return reverse("supplier:supplier_list") def form_valid(self, form): supplier = form.save(commit=False) supplier.organisation = self.request.user.userprofile.company supplier.supplier_created_by = self.request.user supplier.save() and my template is a crispy form: <form method="post"> {% csrf_token %} {% crispy form %} <button type="submit" class="w-full text-white bg-blue-500 hover:bg-blue-600 px-3 py-2 rounded-md">Submit</button> </form> When I try to add a new supplier which does not respect contraint, I go to a page : IntegrityError at /supplier/supplier_create/ duplicate key value violates unique constraint "Supplier unique in company" DETAIL: Key (supplier_name, supplier_created_by_id)=(suppl1Phil, 3) already exists. How can django check and send a message in my template (going back to it with infos filled before instead of an ugly error page :-) -
The view awesomeinventory.supplier.views.supplierCreateView didn't return an HttpResponse object. It returned None instead in Create view
My code is: views.py class supplierListView(LoginRequiredMixin, ListView): template_name = "supplier/Supplier_list.html" def get_queryset(self): organisation = self.request.user.userprofile.company return Supplier.objects.filter(organisation=organisation) class supplierCreateView(LoginRequiredMixin, CreateView): template_name = "supplier/supplier_create.html" form_class = SupplierModelForm def get_success_url(self): return reverse("supplier:supplier_list") def form_valid(self, form): supplier = form.save(commit=False) supplier.organisation = self.request.user.userprofile.company supplier.supplier_created_by = self.request.user supplier.save() my urls: from awesomeinventory.supplier.views import ( supplierListView, supplierDetailView, supplierCreateView, supplierContactListView, supplierContactCreateView, supplierContactDetailView, ) app_name = "supplier" urlpatterns = [ path("supplier_list/", view=supplierListView.as_view(), name="supplier_list"), path("supplier_create/", view=supplierCreateView.as_view(), name="supplier_create"), path("<int:pk>/detail/", view=supplierDetailView.as_view(), name="supplier_detail"), path("<int:pk>/update/", view=supplierDetailView.as_view(), name="supplier_update"), path("<int:pk>/delete/", view=supplierDetailView.as_view(), name="supplier_delete"), path("supplierContact_list/", view=supplierContactListView.as_view(), name="supplierContact_list"), path("<int:suppk>/supplierContact_create/", view=supplierContactCreateView.as_view(), name="supplierContact_create"), # int is supplier_id path("<int:pk>/Contact/detail/", view=supplierContactDetailView.as_view(), name="supplierContact_detail"), ] I m able to go to supplier:supplier_list page and it works well. But when I want to create a supplier with supplierCreateView, supplier is create but it seems to have an issue with get_success_url as I have error The view awesomeinventory.supplier.views.supplierCreateView didn't return an HttpResponse object. It returned None instead -
Extremely Slow Django Database Querying
Currently I'm working on a Django web application using the ORM database models. But all the database queries that I make take too long (all take more than 20ms up to 17000ms using MariaDB). I even tried querying on very easy db models without any foreign keys or other relations, maybe three columns (one of them an indexed primary key) and with only a few row entries in the db table (maybe 50 rows). Even those take too long. I'm monitoring all the queries with the Django debug toolbar and it shows that even the html template engine rendering of a QuerySet with only 10 results is extremely slow (10000 - 17000ms). It's unacceptable that a simple query like the following takes longer than 20ms: SELECT * FROM Table LIMIT 10 And yes, the tables have indexed columns like the id as the primary key, I don't query from a view and I pay close attention to when I evaluate the queries. It would be acceptable if a process only queried the database like 10 times per 20-100ms each query (users won't be able to notice a latency of 200-1000ms) but since few processes do need a few more queries … -
Exception Value: Field 'id' expected a number but got <WSGIRequest: POST '/api/checkout/'>
I am having problems with passing the Post request via Vue.js in Django. It keeps getting this error when I try to fill up the form and click buy. What I am doing is that I pass it through an api and try to send it to the database and save it there. The page continues working fine, but on the background nothing happens. In console it says error 500 and when clicking on Network it shows all of that information. I've been following this tutorial while building my own stuff: https://www.youtube.com/watch?v=2Ed3fTYcx-w&list=PLpyspNLjzwBmIDrDOaPkLLuy5YDDNW9SA&index=8&ab_channel=CodeWithStein var productapp = new Vue({ el:'#cartapp', delimiters:['[[', ']]'], store: store, data() { return { first_name: '', last_name: '', birth_date: '', phone: '', email: '', city: '', region: '', address: '', references: '', products: [{{productsstring|safe}}] } }, computed: { numItems: function() { return store.state.numItems }, totalCost: function() { return store.state.totalCost } }, methods: { submitForm() { var data = { 'first_name': this.first_name, 'last_name': this.last_name, 'birth_date': this.birth_date, 'phone': this.phone, 'email': this.email, 'city': this.city, 'region': this.region, 'address': this.address, 'references': this.references, }; fetch('/api/checkout/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, credentials: 'same-origin', body: JSON.stringify(data), }) .then((response) => { console.log('success') console.log(response) }) .catch(function (error) { console.log('Error 2'); }) … -
why Django admin list is not updating the edit from the frontend React js form?
i am trying to make a CRUD app in DRF-Reactjs and following Tania rascia's example i have successfully implemented add, delete, list view. but i am trying to edit the a specific row it is not updating in DRF backend. but the edited row is showing in the frontend. in DRF side views.py: @api_view(['POST']) def TodoUpdate(request, pk): todo = Todo.objects.get(id=pk) serializer = TodoSerializer(instance=todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) i am using cors header to interface between frontend to backend. here is the frontend code for edit: App.js: import React,{Fragment, useState,useEffect} from 'react' import EditList from './components/EditList'; import axios from 'axios' export default function App() { const initialTodoSate = { id: null, title: "", body: "" }; const [todos, setTodos] = useState([]); const [todoList, setTodolist] = useState(initialTodoSate); const [editing, setEditing] = useState(false); useEffect(()=>{ axios.get("http://localhost:8000/api/todo-list",{}) .then(res=>{ setTodos(res.data) }).catch(err=>{ console.log(err) }) },[]) const addTodoList = (todo) => { axios .post("http://localhost:8000/api/todo-create/",todo) .then((res) => { console.log(res.data); todo.id = todos.length + 1; setTodos([todo, ...todos]); }) .catch((err) => { console.log(err); }); }; const deleteTodo = (id) => { setEditing(false); axios.delete(`http://localhost:8000/api/todo-delete/${id}/`) .then(res=>{ setTodos(todos.filter((todo) => todo.id !== id)); }).catch(err=>{ console.log(err) }) }; const updateTodo = ( id,updatedTodo) => { axios .post(`http://localhost:8000/api/todo-update/${id}/`, id) .then((res) => { console.log(res.data); }) .catch((err) … -
Select related and prefetch related for multiple reverse foreign keys with Django?
I'm currently having issues accessing values in a queryset. I have a models.py for my app that is set up like this: class Company(models.Model): name = models.Charfield(max_length=250) class Patient(models.Model): status_choices = [ ('A', 'Current Admission'), ('D', 'Discharged'), ('U', 'Unknown'), ] first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) patient_status = models.CharField( max_length=15, choices=status_choices, null=True, default='U', verbose_name='Patient Status' ) related_company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='patients') class PatientStay(models.Model): admit_date = models.DateField() projected_dc_date = models.DateField(null=True, blank=True) is_active = models.BooleanField(default=False) stay_to_patient_relationship = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='stays') class PatientLOC(models.Model): loc_to_stay_relation = models.ForeignKey(PatientStay, on_delete=models.CASCADE, related_name='locs') level_of_care = models.CharField(max_length=30) loc_start = models.DateField(null=True) loc_end = models.DateField(null=True, blank=True) is_active = models.BooleanField(default=False) What I am trying to do is query this to get (for a particular company) the patients, their related stay (filtered for only active), and their related PatientLOC. A result like this: Company: -Patient --Stay ---PatientLOC's -Patient --Stay ---PatientLOC's -Patient --Stay ---PatientLOC's I have come up with this (less the filtering): company = Company.objects.select_related().prefetch_related('patients__stays', 'patients__stays__locs').get(id=2) Which I can loop through and get the patient and the stays, but I cannot seem to get to the LOC's for those patients. So, I can do something like this: company = Company.objects.select_related().prefetch_related('patients__stays', 'patients__stays__locs').get(id=2) patients = company.patients.all() for patient in patients: ...: print(patient) ...: print(patient.stays.all()) But … -
Django: Filtering a related field by date yields unwanted results
models: class Vehicle(models.Model): licence_plate = models.CharField(max_length=16) class WorkTime(models.Model): work_start = models.DateTimeField() work_end = models.DateTimeField() vehicle = models.ForeignKey(Vehicle, on_delete=models.SET_NULL, related_name="work_times") However when I try to filter those working times using: qs = Vehicle.objects.filter( work_times__work_start__date__gte="YYYY-MM-DD", work_times__work_end__date__lte="YYYY-MM-DD").distinct() I get results that do not fit the timeframe given. Most commonly when the work_end fits to something, it returns everything from WorkTime What I would like to have: for vehicle in qs: for work_time in vehicle.work_times: print(vehicle, work_time.work_start, work_time.work_end) -
How does the form set work when saving the information?
I was developing an application which used formset, but at the time I was developing, they generated multiple doubts which were, because the data that persists in the database with formset has to be given a different treatment, that is, because you have to modify the formset.instance. This is my inlineformset: ProjectFormSet = inlineformset_factory( Project, Task, form=TaskForm, fields=['type_task', 'task', 'status'], extra=1, can_delete=True ) This is my CreateView: class ProjectCreateView(CreateView): template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: context['formset'] = ProjectFormSet(self.request.POST) else: context['formset'] = ProjectFormSet() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.save() return super().form_valid(form) If I leave the view like this it will generate an error where it will say that formset.save() is prohibited to avoid data loss due to an unsaved related object, but if I modify the formset.instance if it is saved correctly: class ProjectCreateView(CreateView): template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.POST: context['formset'] = ProjectFormSet(self.request.POST) else: context['formset'] = ProjectFormSet() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance … -
Wrong template rendering
I don't understand why django wont render any other template , but home with this code: urlpatterns = [ url(r'^login/', login_page), url(r'^admin/', admin.site.urls), url(r'^contact/', contact_page), url(r'^about/', about_page), url(r'$', home_page), ] But as soon as I delete the home url , every url works just fine. Yes , I did join the base dir with the templates one. Also , it might be useful to add that Im using django 1.11. Thank you ! -
Django modify objects using key=value options
I'm doing http POST processing of incoming data modifications requests (from a DataTables table) for objects in my Django environment. The POST data comes to me in key=value pairs. The problem I'm running into is that I haven't found a way to turn this into something I can use. Django objects and modifications are done like this: id = 123 item = Stuff.objects.get(id=id) item.title = "New Title" item.save() I have the following data attributes: id = 123 attribute = "title" value = "New Title" How can I use them to modify a Django object? -
Why is django not sending my email and instead giving me an error?
I'm trying to get django to send an email but I get as a return in my terminal the print from my else that says there was a problem and it wasn't sent. Why is this happening? This is the code with the email: from django.core.mail import EmailMultiAlternatives from . import views def constancia_email(email): subject, from_email, to = 'Constancia Monotributo', 'bosi@outlook.es', email text_content = 'Hi, this is your pfd.' html_content = '<p><strong>Hi!</strong></p> <p>This is your pdf</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) attachment = open('constancia.pdf', 'rb') msg.attach('constancia.pdf', attachment.read(), 'text/pdf') msg.content_subtype = 'html' msg.attach_alternative(html_content, "text/html") msg.send() This is the view part with the email: #send email constancia_email(email) if constancia_email == True: print("Sus datos fueron enviados correctamente, en un máximo de 2 hs. estarás recibiendo tu constancia por email.") else: print("No hemos podido procesar su solicitud, por favor reintente nuevamente más tarde.") I added this to my settings because I was getting an error but I'm not sure if this helps because I just get the email in my console but it still isn't sent: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'