Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use djangos send email module with model forms
I'm trying to figure out how to fill out the send_mail function when using a model form, to send a confirmation email to the user that fills out the form. class DeliveryForm(forms.ModelForm): class Meta: model = Delivery fields = ('full_name','email', 'phone', 'address', 'city', 'postal') # Create your views here. def info_view(request): if request.method == "POST": form = DeliveryForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('thanks')) form = DeliveryForm() return render(request, 'info.html', {"form": form}) -
Django get value from text input
Currently, I have a django page to display a table of OrderHistory objects. It looks like: {% extends 'base.html' %} <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- Import Jquery Here--> {% load static %} {%block content%} <p style="color: white;">There are {{ unread }} pending requests</p> <table class="table" style="color:white;"> <thead> <tr> <th scope="col">Status</th> <th scope="col">Concept</th> <th scope="col">Department</th> <th scope="col">Location</th> <th scope="col">Type</th> <th scope="col">User</th> <th scope="col">Quantity</th> <th scope="col">Order Date</th> <th scope="col"></th> <th scope="col"></th> </tr> </thead> <tbody> {% for e in orders %} {% if not e.order_read %} <tr style="background-color: grey;"> {% else %} <tr> {%endif%} <th> {% if e.order_read %} Read {% else %} Unread {%endif%} </th> <th>{{ e.order_concept }}</th> <th>{{ e.order_department }}</th> <th>{{ e.order_location }}</th> <th>{{ e.order_type }}</th> <th>{{ e.order_user_name }}</th> <th>{{ e.order_quantity }}</th> <th>{{ e.order_date }}</th> <th> <input type='text' id='tracking_number'></th> <th> <a href="/main/update_order/{{ e.id }}"><button type="submit" class="btn btn-primary" onclick="location.">Complete</button></a> </th> </tr> {% endfor %} </tbody> </table> {% endblock %} With the respective view and url's set up as follows: def update_order(request,pk): #save tracking number to this #send email with tracking number to user order = get_object_or_404(OrderHistory, pk=pk) order.order_read = True order.order_fulfillment_date = datetime.now() order.save() response = redirect('order_history') return response urls.py path('update_order/<str:pk>', views.update_order, name='update_order'), However I would like to add in an extra step where … -
Environment Variables in DevOps and Azure App Service
I am currently struggling to persist environment variables through my DevOps deployment pipeline to Azure App Service. I am deploying a Django app on Azure App Service with Docker containers and Azure's Container Registry. The containers are built on Azure DevOps and pushed to the registry via a release pipeline. I need to keep a few environment variables secret since the app will connect to our Azure Cosmos DB, and I'm doing so by using a tokenized .env file. The variables are kept secret and added to my '.env-prod' file with pipeline variables and the Replace Tokens DevOps task during the build. Here is what my '.env-prod' file looks like: PRODUCTION_KEY=#{{PRODUCTION_KEY}}# AZURE_DB=#{{AZURE_DB}}# AZURE_CONNECT=#{{AZURE_CONNECT}}# ... The tokens are getting properly replaced during the build on DevOps, and the build executes without errors to push containers to our Azure container registry. Now the problem arises when I launch the app on App Service via the docker compose script also used to build the containers. Here is the backend-service in my compose file which builds and runs the Django app: backend-service: env_file: backend_folder/.env-prod build: backend_folder # Container registry name in Azure image: **.azurecr.io/**:0.1.1 volumes: - static:/app/static command: gunicorn django_proj.wsgi:application --chdir django_proj --bind 0.0.0.0:8001 … -
heroku templates does not exist
I tried deploying my project on Heroku, and I get a "template does not exist" error... in my setting 2: have iterated between using and [str(BASE_DIR.joinpath('templates'))], it still doesn't work. In my previous deployment(a different app)i used just Templates and it worked perfectly back then. -
Django 'model' object is not iterable error
I have a problem that I would like you to help me. I have a list of users that shows fine, but when I try to edit a user I get the error: Django 'Residente' object is not iterable. This is my code: residente_list.html <div class="card-body"> {% if not obj %} <div class="alert alert-info">No hay Residentes</div> {% else %} <table class="table table-striped table-hover"> <thead> <th>Nombres</th> <th>Genero</th> <th>T.Documento</th> <th>N.Documento</th> <th>Residencia</th> <th>Estado</th> <th class="all">Acciones</th> </thead> <tbody> {% for item in obj %} <tr> <td>{{ item.nombre_completo }}</td> <td>{{ item.genero }}</td> <td>{{ item.t_doc }}</td> <td>{{ item.numero_doc }}</td> <td>{{ item.residencia }}</td> <td>{{ item.estado|yesno:"Activo, Inactivo" }}</td> <td> <a href="{% url 'res:residentes_edit' item.id %}" class="btn btn-warning btn-circle" role="button"><i class="far fa-edit"></i></a> <a href="#" class="btn btn-danger btn-circle" role="button"><i class="far fa-trash-alt"></i></a> </td> </tr> {% endfor %} </tbody> </table> {% endif %} </div> views.py class ResidenteEdit(LoginRequiredMixin, generic.UpdateView): model = Residente template_name = "res/residente_form.html" context_object_name = "obj" form_class = ResidenteForm success_url = reverse_lazy("res:residentes_list") login_url = 'bases:login' success_message = "Residente Editado Satisfactoriamente" urls.py path('residentes/edit/<int:pk>', ResidenteEdit.as_view(), name='residentes_edit'), models.py class Residente(models.Model): nombre_completo = models.CharField( max_length=100, unique=True) genero = models.ForeignKey(Genero, on_delete=models.CASCADE) t_doc = models.ForeignKey(Tdocs, on_delete=models.CASCADE) numero_doc = models.CharField(max_length=100) residencia = models.ForeignKey(Predio, on_delete=models.CASCADE) estado = models.BooleanField(default=True) Thanks for help -
How to convert FileField query object into bytes in Django?
In this Django project "root" is the main project and "crypt" is the app. What I'm trying to do is, take a user input (file) and then encrypt it. User input is submitted through a form. The form is working just fine and also storing the file inputs. Here is models.py FUNCTION_CHOICE = ( ('ENCRYPT', 'Encrypt'), ('DECRYPT', 'Decrypt'), ) class Cryptdb(models.Model): function = CharField(max_length=7, choices=FUNCTION_CHOICE, default='Encrypt') userinputfile = FileField(upload_to='inputs/') key = CharField(max_length=100, null=True) encryptedfile = FileField(upload_to='encrypted/', null=True) forms.py class InputForm(forms.ModelForm): class Meta: model = Cryptdb fields = ('function', 'type', 'userinputfile') views.py def upload_file(request): if request.method == 'POST': save_the_form = InputForm(request.POST, request.FILES) if save_the_form.is_valid(): save_the_form.save() return HttpResponseRedirect('/success/url') else: form = InputForm() return render(request, 'home.html', {'form': form}) class MainpageView(CreateView): model = Cryptdb form_class = InputForm success_url = 'download' template_name = 'home.html' class DownloadpageView(ListView): model = Cryptdb template_name = 'download.html' context_object_name = 'obj' def get(self, request): form = InputForm() thefile = Cryptdb.objects.order_by('-id')[:1].get() foo = thefile.userinputfile keyy = Fernet.generate_key() key_object = Fernet(keyy) enc = key_object.encrypt(foo) foo.encryptedfile = enc args = {'form': form, 'thefile': thefile} return render(request, self.template_name, args) Here, I used queryset get() method to take the object instead of queryset list and I'm using that object to separate the file and store it … -
Add a string before product name
In the following code, I would like to add a string called "ABC" before appending the product name table_po= set() for tr in orders: table_po.add(str(tr.product)) table_data.append(table_po) After execution, it could be like ABC = Cat where Cat is the {tr.product} value -
content security policy blocking inline execution
I am working on a project in Django, where I am using a javascript from an external payment provider. Upon calling their script, they will insert a payment form embedded in my page. The documentation on how to integrate with their service is found here. Specifically I am following step 3 and 4. A snippet of my html is as below. Upon calling my javascript the payment form from checkout.js will be rendered as an iframe in the checkout-container-div element <div id="checkout-container-div"> </div> <script src="https://test.checkout.dibspayment.eu/v1/checkout.js?v=1"></script> In my javascript, I first call my backend to get the paymentId. Then using the obtained paymentId, I am calling the external checkout.js with const checkout = new Dibs.Checkout(checkoutOptions); in order to render the payment form document.getElementById("paymentButton").addEventListener("click", function() { //Collect all the fields value and send it to the server console.log("pay button clicked") $.ajax({ url : "localDeliveryPayment", type : "get", success: function(response) { if (response['paymentIdCreation'] == true) { console.log(response); const checkoutOptions = { checkoutKey: response['checkoutKey'], // Replace! paymentId: response['paymentId'], containerId: "checkout-container-div", }; const checkout = new Dibs.Checkout(checkoutOptions); checkout.on('payment-completed', function (response) { window.location = 'completed.html'; }); } } }) }) From Google Chrome's console I get the following error related to test.checkout.dibspayment.eu/:1 Refused to execute inline … -
What is the user of sentinel method in Django?
I have seen sentinel methods being used while setting foreign relationship to users, what exactly is the use of these methods? -
Django load huge data to drop down list (select) quicker?
I’m new to django, I have a application with search + drop down field where data load from database which contains 5000+ records, to load data it is taking 30-40 sec, this is not I expected. Is there a better way to load data faster? Any idea/thoughts/example appreciated. -
Is there a way to use Next.js API Routes to Authenticate Django Rest Framework backend?
I'm using DRF as a backend to Next.js frontend. I followed this very fine tutorial to set up authentication, but I read I should use Next.js API Routes as proxy to the DRF API Routes and I can do that on any route other than the authentication one because I must send the X-CSRFToken and credentials: "include" in the request headers. Currently I'm getting the CSRF Token on page load with useEffect: useEffect(()=> { fetch("http://localhost:8000/api-auth/csrf",{ credentials: "include" }) .then( res => setCsrf(res.headers.get("X-CSRFToken"))) .catch( err => console.error(err)) },[]) Im using a direct route to DRF API "http://localhost:8000/api-auth/csrf" instead of a Next.js API like "/api-auth/csrf". The same happens with the handleLogin function: const handleLogin = async (event) => { event.preventDefault(); fetch("http://localhost:8000/api-auth/login/", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrf }, credentials: "include", body: JSON.stringify(formValues), }) .then(() => Router.push("/profile")) }; It is working like this, but I can't set credentials using Next.js API Routes. Even using the same pattern it doesn't work. I think I'm missing some fundamental concept here and I looked it up but couldn't find. If anyone can help I'd appreciate :) -
How to re-upload/Update data with django-import-export
I have uploaded data into the system. I however went ahead and edited soe of the data in the excel, meaning there are changes in that excel. When I want to re-upload so that the changes made can reflect, it doesn't accept. I can't tell why. It says like such data already exists in the system. I have skip_unchanged = True but that isn't helping. Is my model setup having a hand in this? unique_together = ("school", "student_id",)? class ImportStudentsResource(resources.ModelResource): def __init__(self, school_id,klass,*args, **kwargs): super().__init__() self.school_id = school_id self.klass = klass self.fields["id"] = fields.Field(widget=ForeignKeyWidget(Student,'id')) self.fields["stream"] = fields.Field(attribute="stream",column_name="stream",widget=StreamForeignKeyWidget(klass,),) def before_save_instance(self, instance, using_transactions, dry_run): instance.school_id = self.school_id instance.klass_id = self.klass#2 def before_import_row(self, row, **kwargs): row['stream'] = row['stream'].lower() class Meta: model = Student import_id_fields = ('id',) fields = ('student_id','name','year','stream') import_order = ('student_id','name','year','stream') skip_unchanged = True The view . class uploadF1Students(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'libman/upload_student.html',self.context) def post(self, request): klass = get_object_or_404(Klass,school_id=request.user.school.id,name=1).id school_id = request.user.school.id form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) resource = ImportStudentsResource(school_id,klass) try: result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) except Exception … -
using curly double brackets inside another curly double brackets in django template
I started studying Django few days back, while doing a project I came across a situation. In the views.py, I'm passing def chat_rooms(request): context = dict() context['title'] = 'Chat' rooms = Chat_rooms.objects.filter(Q(user1 = request.user.id) | Q(user2 = request.user.id) ) context['rooms'] = rooms for room in rooms: rmssg = Chats.objects.filter(room_id = room.id) lmssg = Chats.objects.latest('id') context[str(room.id)] = lmssg return render(request,'previlageGroup/chat_rooms.html',context) In the Django template,chat_room.html {% for room in rooms %} <div class="card" style="width: 100%;"> <a href="{% url 'pgroup:chat.screen' room.id %}"> <div class="card-body"> <p class="card-text"> {{ {{room.id}}.message}} </p> </div> </a> </div> {% endfor %} In models.py class Chat_rooms(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user1') user2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user2') created_on = models.DateTimeField(auto_now_add=True) class Chats(models.Model): date = models.DateTimeField(auto_now_add=True) has_viewed = models.BooleanField(default= False) message = models.CharField(max_length = 200) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') room = models.ForeignKey(Chat_rooms, on_delete=models.CASCADE) Django is giving me a error, that {{ {{room.id}}.message }} is not possible. How can I do this? Is there any other way? Thanks in advance -
Error when deploying django web application with daphne: Requested setting INSTALLED_APPS, but settings are not configured
I have been battling with an error that I encountered when trying to deploy a django application that uses channels. Error in heroku logs Starting process with command `daphne friendship.asgi:application --port 52589 --bind 0.0.0.0 -v2` 2021-06-02T19:51:57.338171+00:00 heroku[web.1]: Process exited with status 1 2021-06-02T19:51:57.105387+00:00 app[web.1]: Traceback (most recent call last): 2021-06-02T19:51:57.105477+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2021-06-02T19:51:57.105796+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2021-06-02T19:51:57.105861+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 170, in entrypoint 2021-06-02T19:51:57.106200+00:00 app[web.1]: cls().run(sys.argv[1:]) 2021-06-02T19:51:57.106259+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/cli.py", line 232, in run 2021-06-02T19:51:57.106713+00:00 app[web.1]: application = import_by_path(args.application) 2021-06-02T19:51:57.106774+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/daphne/utils.py", line 12, in import_by_path 2021-06-02T19:51:57.107059+00:00 app[web.1]: target = importlib.import_module(module_path) 2021-06-02T19:51:57.107118+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-06-02T19:51:57.107436+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-06-02T19:51:57.107491+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-06-02T19:51:57.107783+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-06-02T19:51:57.107986+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-06-02T19:51:57.108196+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-06-02T19:51:57.108533+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 790, in exec_module 2021-06-02T19:51:57.108768+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-06-02T19:51:57.108967+00:00 app[web.1]: File "./friendship/asgi.py", line 5, in <module> 2021-06-02T19:51:57.109233+00:00 app[web.1]: import errands.routing 2021-06-02T19:51:57.109290+00:00 app[web.1]: File "./errands/routing.py", line 2, in <module> 2021-06-02T19:51:57.110045+00:00 app[web.1]: from . import consumers 2021-06-02T19:51:57.110094+00:00 app[web.1]: File "./errands/consumers.py", line 3, in <module> 2021-06-02T19:51:57.110331+00:00 … -
How do I get stripe's application fee to reflect the adjustable quantity during checkout?
I added the adjustable quantity for Stripe's check out session call. I understand that the fee object is created after the payment. I'm looking at the application fee object in stripe's documentation and it says it is capped at the final charge amount. How do I retrieve the charge amount or better, quantity during the checkout session? checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], customer=customer.id, payment_intent_data={ 'application_fee_amount': int(stripe_price * fee_percentage), 'transfer_data': { 'destination': seller.stripe_user_id, }, }, line_items=[ { 'price_data': { 'currency': currency, 'unit_amount': price, 'product_data': { 'name': title }, }, 'adjustable_quantity': { 'enabled': True, 'minimum': 0, 'maximum': available_quantity, }, 'quantity': 1, }, ], metadata={ "product_id": product.id, "client_reference_id": user.id, }, mode='payment', ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) -
Django Class Based Views Flow
My app is data driven with a postgres db. When a user first sees my “customers” page I would like all existing db entries to be displayed. This part I am using ListView in my class based view. I would also like for these fields to be update-able, removable, as well as have the ability to create new entries. What is the proper way to implement this? -
Django display foreign key on admin dashboard when inheriting from AbstractUser not working?
I'm having a model like a restaurants model from django.db import models class Restaurants(models.Model): name = models.CharField(max_length=200) description = models.TextField(max_length=250) location = models.CharField(max_length=200) rating = models.DecimalField(null=True,decimal_places=2,max_digits=5) def __str__(self): return self.name class Meta: db_table = "Restaurants" verbose_name_plural = "Restaurants" And three different User models: from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from restaurants.models import Restaurants class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) … -
Add a field in the database using the Django function
this is my model class : class complete_taxi_driver_account(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) STATUS_CHOICES = (('woman', 'Woman'), ('man', 'Man'),) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) phone_number = models.CharField(max_length=11) life_place = models.CharField(max_length=120) birth_date = models.DateTimeField(null=False, blank=False) gender = models.CharField(max_length=25, choices=STATUS_CHOICES, default='man') number_plates = models.CharField(max_length=8) national_code = models.CharField(max_length=10) car_number = models.CharField(max_length=50) name_and_type_of_car = models.CharField(max_length=50) # Check if this car is taxi , this field will change to True else False confirmation = models.BooleanField(default=False) # If the taxi app starts, this section will change True, meaning the taxi is ready to pick up passengers online = models.BooleanField(default=False) #I do not know what to do here to add these two fields to the database when this function is called def location(self): # Location of the taxi lat = models.DecimalField(max_digits=20, decimal_places=10) lng = models.DecimalField(max_digits=20, decimal_places=10) I want to have a function in the model class that, when called, creates two fields in the database and fills them in, and from now on be updated by calling it. How can I do this? -
DRF, in perform_authentication() the test for request.user is set to an empty string only when multiple tests are run
When I run a test by itself the test always passes, but when run even with one other test in the same test class it fails. I've tracked down the cause to the perform_authentication() method not having the AnonymousUser set instead, it is set to an empty string. This is not happening on all tests but maybe 20% of the 415 tests I've written. The change I made to the code was to use the Authorization header and removed the code that put credentials in the body of the login request. This should not have affected most of the tests that are now failing. If I override the perform_authentication() by catching the exception and just exiting the method the test works fine, but this is not what I want to do obviously. I would show code, but am not sure what to show. The tests have many layers since the same tests need to be done on many endpoints. Does anybody have a better idea as to how this authorization works? -
ReactJS How can I edit user with functional component useSelector
With the code I have, I am getting the user in input but the input won't change when I type here is the input <div className="pInput"> <label>last Name</label> <input type="text" className="ppInput" value={user.last_name} onChange={(e) => HandleEditDesc(e)} placeholder={user.last_name} /> </div> Here is my on change function e.preventDefault() user.last_name = useSelector((state) => e.target.value); state.auth.user.last_name = user.last_name } Here is how I am getting the user import React from "react"; import { useSelector } from "react-redux"; import { Link } from "react-router-dom"; import Axios from "axios"; const Profile = () => { const user = useSelector((state) => state.auth.user); const subscriptionStatus = useSelector( (state) => state.auth.subscriptionStatus ); I am using Django as my backend -
Filtering three related models in django-filter
I have three models in my models.py file: models.py ################################## Application models ################################## class attack(models.Model): attack_name = models.CharField(max_length=200) defense_mechanism = models.CharField(max_length=200) def __str__(self): return self.attack_name ACTIONS = ( ('malware', 'Malware'), ('hacking', 'Hacking'), ('social', 'Social'), ('misuse', 'Misuse'), ('physical', 'Physical'), ('error', 'Error'), ('environmental', 'Environmental') ) class action(models.Model): action = models.CharField(max_length=15, choices=ACTIONS) attacks = models.ManyToManyField(attack) def __str__(self): return self.action ATTRIBUTES = ( ('confidentiality', 'Confidentiality'), ('integrity', 'Integrity'), ('availability', 'Availability') ) ACTORS = ( ('external', 'External'), ('internal', 'Internal'), ('partner', 'Partner') ) class security_incident(models.Model): asset = models.CharField(max_length=200) #one asset actor = models.CharField(max_length=15, choices=ACTORS) #one actor action = models.ForeignKey(action, on_delete=models.CASCADE) # one security incident can have several actiobns attributes = models.CharField(max_length=15, choices=ATTRIBUTES) #as many attributes as wished, should be two for hierarchial tree def __str__(self): return self.asset I am trying to filter these models in a django-filter filterset: class SecIncFilter(django_filters.FilterSet): asset = django_filters.CharFilter(lookup_expr='icontains', distinct=True, label='Search for security incidents, related attacks and defense mechanisms to an asset') attributes = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple(), choices=ATTRIBUTES, label='Choose categories') action = django_filters.MultipleChoiceFilter(name='action') class Meta: model = security_incident fields = ['asset','attributes'] def __init__(self, *args, **kwargs): super(SecIncFilter, self).__init__(*args, **kwargs) # at sturtup user doen't push Submit button, and QueryDict (in data) is empty if self.data == {}: self.queryset = self.queryset.none() And then rendering results into this … -
display different elements based on even and odd in Django html template
I am a noob at django. And I faced this problem: dest over here is a list which is coming from views.py. I want to use this(code below) for even occurrences : <div class="row no-gutters"> <div class="col-lg-6 order-lg-2 text-white showcase-img" style="background-image:url( {{baseUrl}}/{{dest.img}} );"><span></span></div> <div class="col-lg-6 my-auto order-lg-1 showcase-text"> <h2> {{dest.name}} </h2> <p class="lead mb-0">{{dest.desc}}</p> The Price : <p class="lead mb-0" style="font-weight:bold">Rs. {{dest.price}}</p> </div> </div> and this(code below) for odd positions : <div class="row no-gutters"> <div class="col-lg-6 text-white showcase-img" style="background-image:url(&quot;{% static 'img/bg-showcase-2.jpg' %}&quot;);"><span></span></div> <div class="col-lg-6 my-auto order-lg-1 showcase-text"> <h2>Updated For Bootstrap 4</h2> <p class="lead mb-0">Newly improved, and full of great utility classes, Bootstrap 4 is leading the way in mobile responsive web development! All of the themes are now using Bootstrap 4!</p> </div> </div> how to achieve this ? -
Refresh <div> element in a Django html template
How can I refresh an element within a Django HTML template Example <div class="container" id="myForm"> <form action="/cgi-bin/hello_get.cgi" method="get"> Fill the Detail: <br/> <textarea rows="5" cols="50" name="description">{{ bar_codes }} </textarea> <input type="submit" value="submit"/> </form> </div> I have JavaScript code that tries to refresh the div element with id myform. <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'detect_barcodes' %}, // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#myForm').append(response); append_increment += 10; }); }, 10000) </script> the variable bar_codes data gets being updated contantly. The data is not from an api but from a barcode scanner. This is the view def detect(request): stream = CameraStream() success, frame = stream.camera.read() if success: status = True else: status = False bar_codes = stream.used_codes print(bar_codes) return render(request, 'detect_barcodes/detect.html', context={'bar_codes': bar_codes, 'cam_status': status}) This is the url.py file urlpatterns = [ path('', views.detect, name='detect_barcodes'), path('camera_feed', views.camera_feed, name='camera_feed'), ] -
How to sort and search a time field in 12 format? DRF
I have two fields of type time in postgresql, which saves these values in 24 format (03:30 PM would save 15:30:00). How can I run a search with a time in format 12 and match it with its equivalent in format 24? How can I order these fields in 12 format? the fields are 'ho_inicio' and 'ho_fin'. My Viewset (I override the list method to search regardless of accents): class HorasEscolaresViewSet(ListModelPagination, viewsets.ModelViewSet): queryset = TbledcHora.objects.all() serializer_class = HorasEscolaresSerializer filter_backends = [DjangoFilterBackend, AliasedOrderingFilter] filterset_class = HorasEscolaresFilter search_fields = ['id_nivel_academico__nb_nivel_academico', 'nu_hora'] filterset_fields = ['id_nivel_academico', 'in_status'] ordering_fields=('id_nivel_academico', 'nu_hora', 'ho_inicio', 'ho_fin') ordering= 'id_nivel_academico' renderer_classes = (EmberJSONRenderer, ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if "search" in request.GET: if request.GET['search'] != '': q_list = [] q_list.append(Q(id_nivel_academico__nb_nivel_academico__unaccent__icontains=request.GET['search'])) queryset = queryset.filter(reduce(operator.or_, q_list)) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many = True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) My serializer: class HorasEscolaresSerializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] ho_inicio = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats) ho_fin = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats) class Meta: model = TbledcHora fields = '__all__' depth = 1 -
Why my user model is not saving even after the code is running successfully
I want to create a social media web app. I am currently working on the signup functionality Please help me find why my user model is not saving My models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser import string import random # Create your models here. def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if ProfileUser.objects.filter(user_name=code).count() == 0: break return code class ProfileUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name = models.SlugField( unique=True, max_length=30, default=generate_unique_code) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] My SignUp View class signUpView(APIView): def get(self, request, format=None): try: user_name = request.GET.get("name") password = request.GET.get("password") email = request.GET.get("email") first_name = request.GET.get("first_name") last_name = request.GET.get("last_name") except Exception as e: print(e) return Response({"Invalid Data": "Not Enough Data"}, status=status.HTTP_206_PARTIAL_CONTENT) user = ProfileUser(email=email, user_name=user_name, first_name=first_name, last_name=last_name, password=password) user.save() return Response({"User Created": { "name": user_name, "email": email, "password": password }}, status=status.HTTP_201_CREATED) I am a beginner in Django