Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enable editing a field in Django admin's list view
Consider a model that stores application forms. I would like to use Django admin to quickly view applications and change their status. I would like to be able to change the status of an application right in the view listing all the applications without having to open each application for editing. So, is it possible to make a field editable right in the admin list view? -
How to return sum according to date range in django?
It'd be really nice if someone could help me with this. I've stuck here. I'm able to do this manually but how to do according to user input. Payment.objects.filter(created_by=42, mode='cash', created_at__range=["2021-11-01", "2021-11-04"]).aggregate(Sum('amount')) Here created_by and date_range I'm sending in url like this : http://127.0.0.1:8000/api/v1/registration/?created_by=42&start_date=2021-06-06&end_date=2021-11-18 so the id created by and date_range will always change. And according to change the sum will return. My Model : class Payment(TimestampedModel): customer_visit = models.ForeignKey( CustomerVisit, on_delete=models.CASCADE, null=True, related_name="customer_payments" ) mode = models.CharField(choices=PAYMENTCHOICES, max_length=25) amount = models.FloatField() ref_no = models.TextField(null=True) bank = models.ForeignKey( "BankDetails", on_delete=models.CASCADE, null=True, related_name="payment_bank" ) is_settlement = models.BooleanField(default=False) created_by = models.ForeignKey("Employee", on_delete=models.DO_NOTHING, null=True,related_name='payment_created_by') updated_by = models.ForeignKey("Employee", on_delete=models.DO_NOTHING, null=True,related_name='payment_updated_by') My View : class UserWiseCollectionView(ListAPIView): permission_classes = [ IsAuthenticated, ] pagination_class = CustomPagination model = CustomerVisit serializer_class = UserWiseCollectionSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['created_by'] def get_queryset(self): start_date = self.request.query_params.get("start_date") end_date = self.request.query_params.get("end_date") emp_id = self.request.query_params.get("emp_id") items = self.model.objects.all() if start_date and end_date: items = items.filter( created_at__range=[start_date, end_date] ) if emp_id is not None: items = items.filter(phelebotomist_id = emp_id) return items -
Django: Load JSON into Bootstrap table with AJAX function + Missing Data
I want to create a simple application that can discover data from a database (a live program) with Django. One of the features is to display the list of tables. A response API that contains the list of table names from a database has been created: { "message": "success", "results": [ { "schema": "public", "table": "actor" }, { "schema": "public", "table": "actor_info" }, { "schema": "public", "table": "customer_list" }, { "schema": "public", "table": "film_list" }, .... ] } Then, I want to display the data (from API) in a bootstrap table by creating an AJAX function. This is my HTML file (full code is here): ... <div class="table-responsive"> <table class="table table-sm" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Schema</th> <th>Table Name</th> </tr></thead> <tbody id="divBody"></tbody> </table> </div> ... This is my AJAX function (Currently, I used the GET method. I want to change into POST method later): <script> $(document).ready(function () { BindTables(); }); function BindTables(){ $.ajax({ type:"GET", dataType: "JSON", url: "http://127.0.0.1:8000/api/v1/table/", success: function(data){ console.log("It's success"); console.log(data.results) var structureDiv = ""; for (let i=0; i < data['results'].length; i++){ structureDiv += "<tr>" + "<td>" + data['results'][i].schema + "</td>" + "<td>" + data['results'][i].table + "</td>" + "</tr>" } $("#divBody").html(structureDiv); } }); } </script> Currently, I can … -
object of type 'map' has no len()
I tried run my docker image for my django project and I have got a error. I research on google but could not any solution. Can anybody help me please! Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/code/Eventful-main/eventful/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
How can I upload images to a specific user in a self-created user table in Django?
I get an MultiValueDictKeyError with this code: I created 2 models one for the users and one for the photos. When a user is logged in, the user must upload a photo in the upload.html. The relationship between the user and photos models is one-to-many. I am strugling to upload the image, because of the foreign key value that must be retrieved from the loggin.html to the gallery.html then to the upload.html. My models: from django.db import models import os from django.contrib.auth.models import User class users(models.Model): username = models.CharField(max_length=20) email = models.EmailField() password = models.CharField(max_length=105) def __str__(self): return [self.username, self.email, self.password] def filepath(request, filename): return os.path.join('uploads/', filename) class photos(models.Model): user = models.ForeignKey(users, on_delete=models.CASCADE) title = models.CharField(max_length=20) description = models.CharField(max_length=100, null=True) location = models.CharField(max_length=50, null=True) image = models.ImageField(upload_to="media/") def __str__(self): return [self.user_id, self.title, self.description, self.location, self.image] My urls: from django.urls import path from . import views urlpatterns = [ path("index/", views.index, name="index"), path('', views.login, name="login"), path('login/', views.login, name="login"), path('test/', views.test, name="test"), path('register/', views.register, name="register"), path('gallery/', views.gallery, name="gallery"), path('upload/<int:user_id>/', views.upload, name="upload"), ] My views: from django.contrib.auth.decorators import login_required from django.db import transaction from django.shortcuts import render from main.models import users from main.models import photos from passlib.hash import sha256_crypt from django.http import HttpResponse … -
django-q multple cron expression for a single job
Is there a way to use multiple cron expression for a single job in Django-Q. I want a schedule a job for different day of different month. want to combine this- At 11:00 on day-of-month 10, 20, and 30 in January and every month from March through December-- 0 11 10,20 1,2,4-12 * At 11:00 on day-of-month 10, 20, and 28 in February.-- 0 11 10,20,28 2 * -
how to show message(Answer must be equal to the choices) and i want to remain on the same page, anyone?
This is my Add Question class #views.py class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) answer = request.POST['answer'] if answer == request.POST['option1'] or answer == request.POST['option2'] or answer == request.POST['option3'] or answer == request.POST['option4']: forms.save() return redirect(reverse('home')) else: print('invalid answer') return redirect(reverse('AddQuestion')) def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) -
Django Queryset : Left outer join multiple tables, group by different column that has same value?
I have following model sturcture : Model A : id misc id misc 1 something 2 randomstuff Model B : id : Foreign Key A.id date amount id date amount 1 2021-11-15 10 1 2021-11-16 15 2 2021-11-16 20 Model C : id : Foreign Key A.id date amount id date amount 1 2021-11-15 1 2 2021-11-16 2 2 2021-11-16 3 So I want to make a queryset where I can Left join three tables, where B and C has a "date" column which, relationwise, not related, but in practice are exact same column. So I want to make an aggregated table, and my desired output is : id date A.amount B.amount 1 2021-11-15 10 1 1 2021-11-16 15 0 2 2021-11-15 20 2 2 2021-11-16 0 3 which basically means joining B and C by id and date. Any regular join attempts obviously gave me like 6+ rows instead (since B.date and C.date is a completely different column in theory and they just outer join for each combination), so I was looking for a way to join two relations with multiple "ON"s. I tried FilteredRelation, as following : res = (qs .annotate(BB=FilteredRelation('B, )) .annotate(CC=FilteredRelation('C',condition=Q(C__date=F('B__date')) )) .values("id","BB__amount","CC__amount") ) print (res.query) … -
How to query Django PostGIS / Postgres DB with the map / Leaflet boundary box view?
Results from query made with other fields are populated on Leaflet: var myMap = L.map("mapid", {zoomControl: false}); L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {maxZoom: 18 }).addTo(myMap); myMap.setView([-34, 151], 12); var markers = [ {% for journal in queryset %} L.marker([{{ journal.latitude }}, {{ journal.longitude }}]), {% endfor %} ] var group = L.featureGroup(markers).addTo(myMap); I now want the results populated by where the user places Leaflet's boundary box, but I'm bewildered on how to do that. I've got GDAL installed, have converted the long / lat cols to a spatial col in Postgis with ADD COLUMN geom geometry(Point, 4326) GENERATED ALWAYS AS (ST_SetSRID(ST_MakePoint("longitude", "latitude"), 4326)) STORED, added geom = models.PointField(blank=True, null=True) to models.py, but am lost on where to go from here. Someone has suggested I incorporate this into a view but I don't know how to make sense of it: from django.core.serializers import serialize entries = Entry.objects.all() data = serialize('geojson', entries, geometry_field='point', fields=('id', 'name',)) This seems the most authoritative tutorial on the topic but I'm totally lost when he gets to views and talks of a generic class based view / list views / Django Rest Framework. Is there a dumbed down explanation somewhere? I feel like an idiot. Unsure if relevant but the table … -
Is there a way to show login error in Django?
I have a custom login page for my web. Upon keying the right account details, I can log in to my web. But if I key in wrong account details, it just refreshes the pages with the username and password 's textbox empty. Is there some way to show something like 'Username or Password is wrong' as a error or message? Within the login.html I have the following {% if messages %} {%for message in messages%} <div class ="alert alert-success" role="alert"> {{message}} </div> {%endfor%} {%endif%} {% for field in form %} {% if field.errors %} {% for error in field.errors %} <div class="alert alert-danger" role="alert"> <div class="d-flex flex-row"> <div class="align-middle pr-2"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-circle-fill" viewBox="0 0 16 16"> <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM5.354 4.646a.5.5 0 1 0-.708.708L7.293 8l-2.647 2.646a.5.5 0 0 0 .708.708L8 8.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 8l2.647-2.646a.5.5 0 0 0-.708-.708L8 7.293 5.354 4.646z" /> </svg> </div> <div class="align-middle"><b>{{field.label}}</b> - {{error}}</div> </div> </div> {% endfor %} {% endif %} {% endfor %} The following does not seem to do anything if the username or password is incorrect. -
Page not found (404) The current path, api/posts/1, didn’t match any of these
I'm trying to create an api through Django rest framework and using NextJS for the frontend. I can get all the post data without any error. but when i try to get data for one post it gives me and error saying "Page not found (404) The current path, api/posts/1, didn’t match any of these." Here all of the files in my api folder api/serilizer.py: [1]: https://i.stack.imgur.com/e132y.png api/urls.py: [2]: https://i.stack.imgur.com/07jTJ.png api/views.py and project/urls.py [3]: https://i.stack.imgur.com/s0g8t.png [4]: https://i.stack.imgur.com/twh9S.png Please tell me what is wrong. Thanks -
Creating choices field based on another modelForms entries
I currently have 2 models, 1 for customers and 1 for JobCards I would like to automatically add the "customers" data into the "JobCards" entries with a choices field. However, I am getting the following error with my code: TypeError: 'newCustomersClass' object is not subscribable Please see the following code class newCustomersClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) customerClass = newCustomersClass.objects.all() customers = [] for row in customerClass: rdict = {} rdict.customerName = row[0] customers.append(rdict) class jobCardsClass(models.Model): customerName = models.CharField(choices=customers ,max_length=100 , blank=False , default=1) Is it possible to append an array like this from a model form? Otherwise, what would be a better way to do so? -
How can I use pdf.js to display the first page of every user-uploaded pdf file as a preview in Django?
Up to now i have successfully display the first page preview for one pdf file but it doesn't work for remaining others. models.py import uuid from django.db import models class PdfUploader(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) docfile = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'pdf_uploader' ordering = ['-uploaded_at'] @property def filename(self): return self.docfile.name.split("/")[4].replace('_',' ').replace('-',' ') views.py class PdfUploadView(CreateView): def get(self, request, *args, **kwargs): context = {'form': PdfUploadForm()} return render(request, 'partials/pdf_upload_form.htm', context) def post(self, request, *args, **kwargs): form = PdfUploadForm(request.POST, request.FILES) files = request.FILES.getlist('docfile') if form.is_valid(): for f in files: file_instance = PdfUploader(docfile=f) file_instance.save() return HttpResponseRedirect(reverse_lazy('pdf-list')) return render(request, 'partials/pdf_upload_form.htm', {'form': form}) pdf_upload_form.htm {% block "content" %} <div role="main" class="main"> <section class="section section-default pt-5 m-0"> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> </div> </section> </div> {% endblock %} pdf_lists.htm By following official official django docs, I am passing a context variable as JSON to the pdf.js. {% for obj in pdfs %} <tr> <td> {{ forloop.counter }} </td> <td> <a href="{{ obj.docfile.url }}" target="_blank" rel="noopener noreferrer">{{obj.filename}}</a> </td> <td> {{ obj.uploaded_at|date:"d-M-Y" }} </td> <td> <a href="{{obj.docfile.url}}" target="_blank" rel="noopener noreferrer"> <canvas id="the-canvas" style="height:250px;"> </canvas> {{obj.docfile.url|json_script:'mydata'}} </a> </td> </tr> {% endfor %} pdf.js Now I'm reading … -
Using a postgres composite field containing a geography type for django ORM usage
So i have a composite field that i want to use in my django models using postgres as the DB. CREATE TYPE address_verbose AS ( contact_person_name string_not_null, mobile string_no_spaces, mobile_cc string_no_spaces, email email_with_check, address text, city text, state text, country text, pincode string_no_spaces, location geography ); The string_not_null, string_no_spaces and email_with_check are just domains i have created for validation. Everything works fantastically if i use SQL, but the thing is want to use this field in a django models and i want to use Django ORM for at least creating, updating and deleting objects containing this field. So after some google search i was able to come up with a custom model field. from typing import Optional from django.contrib.gis.geos import Point from django.db import connection from django.db import models from psycopg2.extensions import register_adapter, adapt, AsIs from psycopg2.extras import register_composite address_verbose = register_composite( 'address_verbose', connection.cursor().cursor, globally=True ).type def address_verbose_adapter(value): return AsIs("(%s, %s, %s, %s, %s, %s, %s, %s, %s, ST_GeomFromText('POINT(%s %s)', 4326))::address_verbose" % ( adapt(value.contact_person_name).getquoted().decode('utf-8'), adapt(value.mobile).getquoted().decode('utf-8'), adapt(value.mobile_cc).getquoted().decode('utf-8'), adapt(value.email).getquoted().decode('utf-8'), adapt(value.address).getquoted().decode('utf-8'), adapt(value.city).getquoted().decode('utf-8'), adapt(value.state).getquoted().decode('utf-8'), adapt(value.country).getquoted().decode('utf-8'), adapt(value.pincode).getquoted().decode('utf-8'), adapt(value.location).getquoted().decode('utf-8'), )) register_adapter(address_verbose, address_verbose_adapter) class AddressVerbose: def __init__(self, contact_person_name: str, mobile: str, mobile_cc: str, email: str, address: str, city: str, state: str, country: str, pincode: str, location: Optional[Point] … -
Encrypting a django field (not a password)
I have an ecommerce website made with django and I want to store details of orders. The fields would have id, thing bought, quantity, total price, etc. Right now I only have them stored as plaintext so I want to make it more secure. Hashing isn't an option because I want to be able to read the data. I though about encryption, but is there any other way? If there isn't I have a few questions, How do I safely encrypt and decrypt the data Where and how do I store the encryption key Will there be just 1 master key? Any help is appreciated! -
How to setup Postman to handle APIs from remote server
I have my django server running in a ssh client (ubuntu) but I want to test the api's in the local window machine. How could I achieve that? -
How to throttle redis/celery tasks for a django web site?
I have a django v3.0.2 site (python v3.6.9) where I upload an image, process the image, and then display it on a web site. By process the image, I create different sizes of the the one image, find and identify faces, ocr any text and translate it if needed, use several different algorithms to calculate how similar each image to the others, and other image processing algorithms. I use celery v4.3.0 and redis v4.0.9 to do all the calculations in the background in different celery tasks. The issue I am having is that when I try to upload and process more than ~4 images in a loop, I run out of memory and the calculations start to throw exceptions. By run out of memory, my 5 GB of swap and 16 GB of ram are all used up and chrome even crashes. In my database, I keep a log of the progress of each task and whether it completes successfully or not. I can see many errors and many tasks not started. If I put a time.sleep(10) in the loop that uploads the images and right after the celery workers are launched for each image, I can upload 60+ images … -
how to save bootstrap modal form upon submit in django?
I'm new to ajax and I need help. I was able to open the modal when I clicked the Add grade, now my problem is how to save the form to the database using modal? that error page will show if I hit the save changes in modal form. views.py class GradeUpdateView(LoginRequiredMixin, UpdateView): model = Subject template_name = 'teacher/modal.html' # fields = ['grade'] # success_url = '/' form_class = UpdateGradeForm def get_success_url(self): subject = self.object.subject_name year = self.object.year_taken return reverse_lazy('student-list', kwargs={"subject_name_id": subject.id, "year_taken": year}) modal.html <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" id="grade-form"> <div class="modal-body"> {% csrf_token %} {{ form.as_p }} {% comment %} <input type="submit" class="btn btn-sm btn-block btn-primary" value="Save"> {% endcomment %} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" data-form-url="" class="btn btn-primary" id="save-form">Save changes</button> </div> </div> </form> </div> </div> </div> main.js var modalDiv = $("#modal-div"); $(".open-modal").on("click", function () { $.ajax({ type: 'GET', url: $(this).attr("data-url"), success: function (data) { modalDiv.html(data); $("#exampleModalCenter").modal(); } }); }); -
Automatically taking picture when face detected using Django?
I successfully used StreamingHttpResponse to open the webcam on a template and detect face. But I don't know how to automatically take picture of the detected face and display it on the template. -
Implementing Pagination with Django-Filter
I am looking to implement Pagination with Django-Filter's function based view. I currently have the search function working, but have not been able to find documentation online on how to implement pagination with Django-filter; haven't been able to get it working with references i've found online. What I have so far: views.py from django.shortcuts import render from .models import Stock from .filters import StockFilter def home(request): return render(request, 'stockwatcher/home.html', {'title': 'Home'}) def stock_search(request): f = StockFilter(request.GET, queryset=Stock.objects.all()) return render(request, 'stockwatcher/search_results.html', {'filter': f}) filters.py import django_filters from .models import * class StockFilter(django_filters.FilterSet): senator = django_filters.CharFilter(field_name='senator' ,lookup_expr='icontains') ticker = django_filters.CharFilter(field_name='ticker', lookup_expr='iexact') class Meta: model = Stock fields = [ 'senator', 'ticker' ] exclude = [ 'asset_description', 'asset_type', 'amount', 'type', 'transaction_date', ] urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.home, name="stockwatcher-home"), path('stocks/', views.stock_search, name="stockwatcher-stocks"), path('about/', views.about, name="stockwatcher-about")] search_results.html {% extends "stockwatcher/base.html" %} {% block content %} {% load widget_tweaks %} <div class="container"> <div class="row" style="padding: 50px;"> <form method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> </div> <div class="row"> {% for stock in filter.qs %} <div class="col-4"> <div class="card text-white bg-info mb-3" style="max-width: 18rem;"> <div class="card-header">{{stock.transaction_date}}</div> <div class="card-body"> <h5 class="card-title" style="color: white"> {{stock.ticker}} </h5> <p class="card-text">{{stock.senator}} - … -
Does anyone know why base appears instead of virtualvenv? Pycharm
Does anyone know why base appears instead of virtualvenv? How can I reactivate it? I am with Pycharm on Windows I was working well with venv and suddenly at night he changed it for base -
Django: Show many objecets values without writing them all
In my model I'have many questions for my user, so when I try to show the results using a for loop my code became kinda big and I'm also afraid of errors. I was wondering if there is a smarter way to display only the "a,b,c" user inputted answers (without the user and the date fields) with way less code. Here what I'm doing since now: model class Question(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) start_date = models.DateField(default=datetime.now) finish_date = models.DateField(default=datetime.now) a = models.CharField(null=True) b = models.CharField(null=True) c = models.CharField(null=True) ... html {% for answer in answers %} {{ answer.a }}, {{ answer.b }}, {{ answer.c }} ... {% endfor %} views def show_answers(request): answers = Question.objects.filter(user=request.user.profile) return render(request, 'show_answers.html', {'answers': answers}) -
How can I have a form redirect to same page after submitting in Django?
How can I set my function in views.py so that a form redirects to the same page after submitting? For example, I want to add time slots: In my views.py: @login_required def post_available_timeslots(request): print("Check") if not check_existing_timeslot(request): print("Time slot does not exist") instance = TimeSlot() data = request.POST.copy() data["time_slot_owner"] = request.user # data["food_avail_id"] = FoodAvail.objects.get(author=request.user).pk form = TimeSlotForm(data or None, instance=instance) if request.POST and form.is_valid(): form.save() return redirect("food_avail:view_food_avail_res") else: print("Time slot does not exist") messages.info(request, "Time Slot Already Exists") return render(request, "food_avail/view_food.html", {"time_slot": form}) in models.py class TimeSlot(models.Model): time_slot_owner = models.ForeignKey(User, on_delete=models.CASCADE) # food_avail_id = models.ForeignKey(FoodAvail, on_delete=models.CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.start_time) + "-" + str(self.end_time) In forms.py: class TimeSlotForm(ModelForm): class Meta: model = TimeSlot fields = ["start_time", "end_time"] In urls.py: from django.urls import path from food_avail import views app_name = "food_avail" urlpatterns = [ path("post_food_avail/", views.post_available_food, name="post_food_avail"), # path("post_food_avail/", views.FoodAvailCreateView.as_view(), name="post_food_avail"), # path("update_food_avail/", views.post_available_food, name="update_food_avail"), path("food_avail_all/", views.check_food_availibility, name="view_food_avail"), path("food_avail_res/", views.view_available_food, name="view_food_avail_res"), # path("food_avail_res/", views.post_available_timeslots, name="create_timeslots"), ] in my html template: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> {{ field.label }} <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for … -
AWS s3bucket "can only concatenate str (not "NoneType") to str"
Im having trouble finding out whats the problem. I don't know what's causing the error if its boto3 or s3bucket , DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' seems to be the problem. At least when I remove DEFAULT_FILE_STORAGE the templates render. I either get 'NoneType' object has no attribute 'encode' for every template or "can only concatenate str (not "NoneType") to str" attempting to upload image. settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ["localdeals1.herokuapp.com", 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Products.apps.ProductsConfig', 'Users.apps.UsersConfig', 'django_filters', 'crispy_forms', 'widget_tweaks', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'Products.context_processors.Products_and_Users', ], }, }, ] WSGI_APPLICATION = 'Ecommerce.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Los_Angeles' USE_I18N = True USE_L10N = True USE_TZ = True GEOIP = os.path.join(BASE_DIR, "Products") STATIC_URL = '/static/' … -
Create a from builder using Django
I am fairly new to programming and start my career with Python Django. I already build some basic application and recently came across to use google forms and decided to create application like this. Where any user can come to certain page and can able to create his own form as per his requirement. I though of some new features like drag and drop. I wanted to ask if that's somehow possible to drag drop input fields or something like that using Django template system where I can use some simple JS library or if its possible using React as fronted. So my requirements are quite simple, but I am confused with Django models that what will be the structure of models. UI should be drag n drop thing. User can select the list of fields available in the inventory. And create his own form. And on post submission. From django you need to capture and store the data. Here in this case the data will be the form fields as well as its values. Ex form fields which are available in the inventory. Test field Email Field Multi select field and Drop Down Field= I hope someone can help …