Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Rest-Framework: Login Serializer Error
I am trying to implement the Login system myself, instead of relying on a third-party application. When I try to login, I get a 400 Bad Request Error saying, user with this email already exists, instead of the data, I want it to return. Login Serializer class UserLoginSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ("email", "password") extra_kwargs = {"password": {"write_only":True}} def validate(self, data): email = data["email"] password = data["password"] user = UserProfile.objects.get(email = email) if user: if not user.check_password(data["password"]): raise serializers.ValidationError("Incoreect Password") return data raise serializers.ValidationError("User Not Found") The LoginAPIView class UserLoginAPIView(APIView): def post(self, request): user = UserLoginSerializer(data = request.data) if user.is_valid(): return Response(user.data, status = status.HTTP_200_OK) return Response(user.errors, status = status.HTTP_400_BAD_REQUEST) -
Django MultiValueDictKeyError for upload file
There has a file upload page for upload file to a object by id in model. However, it shown MultiValueDictKeyError after submitted. I would appreciate if any help. models.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) img_upload = models.FileField(upload_to='payment', null=True) forms.py: class Upload_File(forms.Form): class Meta: model = Order fields = ('img_upload') views.py: def upload_page(request, id): order = get_object_or_404(Order, id=id) form = Upload_File(request.POST or None, request.FILES or None) if request.method == 'POST': order.img_upload = request.FILES['image'] if form.is_valid(): form.save() messages.success(request, 'Succeed') return redirect('user_info') else: form = Upload_File() context = { 'form': form, } return render(request, 'upload.html', context) html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input class="form-group" type="file" name="image/> <button class="form-group" type="submit">Submit</button> </form> -
How to write details of parameters in django api documentation
I want to write details of parameters that are passed to an api in Django. I installed coreapi and added url for docs page: from rest_framework.documentation import include_docs_urls urlpatterns = [ path('admin/', admin.site.urls), path(r'docs/', include_docs_urls(title='API Documentation')) ] In views.py: class CreditAPI(APIView): serializer_class = CreditSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def post(self, request): """ This gets a post request with token and after authentication creates a credit for that user. """ CreditInfo.objects.get(user=request.user) try: currency = request.data.get('currency', None) credit = CreditInfo(currency=currency, user=request.user) credit.save() return Response(status=status.HTTP_201_CREATED) except: return Response(status=status.HTTP_400_BAD_REQUEST) So I have following document page: My question is how can I add details of parameters in a table in this page? -
How can i choose a different python version after set a virtual enviroment ? im on win10
i have 2 version of python installed on my win10 machine 3.6 and 38 depending on my project how to launch one rather than the other ? Do i need to choose before i set the vrtual enviroment ? basically i was wondering after setting my virtual enviroment, how to choose the one i want to use for the project ? any indication? id love to do like i do in choosing django version.. for example pip install django==2.1 , how can i do for choosing python version ? -
How to handle update_fields to work on django?
I've the following code: investor.is_phone_verified = True investor.phone = phone_number investor.save(update_fields=['is_phone_verified', 'phone']) To update a flag and a certain field for investor user. when I try to get that user again and run, it return false: investor.is_phone_verified False Any working way to handle updating fields in django? I also tried: User.objects.filter(pk=user.pk).update(is_phone_verified=True) but also didn't work! -
Deleting a value from many to many field in views.py in django website
I am working on a basic ecommerce django website . My product model has the following: size=models.ManyToManyField(Siz) and this is the size model: class Siz(models.Model): size=models.CharField(max_length=3,null=True,blank=True) desc=models.CharField(max_length=110,null=True,blank=True) I have added the sizes manually in the django administration. What I want is that Whenever a user orders something the value of the size of the product that he ordered automatically is deleted from the product sizes available. This is my orderitem model that has the field of the selected size. class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,) size=models.ForeignKey(Siz,on_delete=models.SET_NULL,null=True) and this is my views that checks when the order (payment for the order) is completed or not. @csrf_exempt def handlerequest(request, id): order=Order.objects.get(id=id) items=order.orderitem_set.all() form = request.POST verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': order.complete=True order.save() else: print(response_dict['RESPMSG']) order.delete() return render(request, 'handlerequest.html', {'response': response_dict,'order':order}) When the order is completed the order.complete is set to true.At that Time I want to deleted the ordered size.Please help me with a way. Thanks -
Recursive query in Django
Models.py from django.db import models from django.contrib.auth.models import User class EmployeeRelation(models.Model): employee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hierarchy_user') reporting_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hierarchy_manager') class SalesLines(models.Model): rep = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sale_user') reporting_day = models.DateField() revenue = models.DecimalField(max_digits=16, decimal_places=4) Views.py from django.http import JsonResponse from typing import List, Union from django.db.models import Sum, Q from .models import EmployeeRelation, SalesLines def get_revenue_by_sales_rep(request, user_id): employeeObj = EmployeeRelation.objects.filter(reporting_to_id=user_id) data = {} if employeeObj: for subject in employeeObj: # the current user is a subject and has managers under him. managerSet = EmployeeRelation.objects.filter(reporting_to_id=int(subject.employee_id)) # if the person below is also a manager if managerSet: for salesrep in managerSet: temp = {} temp = get_revenue_sum(salesrep.employee.id) data = {**data,**temp} else: temp = {} temp = get_revenue_sum(subject.employee.id) data = {**data,**temp} else: data = get_revenue_sum(user_id) return JsonResponse({"revenue": data}) def get_revenue_sum(salesrep_id): salesRepObj = EmployeeRelation.objects.get(employee_id=salesrep_id) full_name = salesRepObj.employee.get_full_name() revenue = "{:.2f}".format(SalesLines.objects.filter(rep_id=salesrep_id).aggregate(Sum('revenue'))['revenue__sum']) return {full_name:revenue} I'm trying to get the revenue of sales rep that works under every user. So a user can be a director, manager, or sales rep. So for instance, if there is a director and a manager works under him then I need to recursively find the revenue of all the sales rep that works under the manager and so on. My … -
Django Horizontal Scroll on Top of Changelist
I have the same problem as depicted here by mozman2: "In my Django changelist there are lots of columns that means there is a scrollbar at the bottom of the list. Is it possible to get a scrollbar to appear at the top so I don't need to scroll down" The solution from the given link seemed to help mozman2. However, I cannot reproduce it. Hence I tried copy-pasting the code from https://github.com/avianey/jqDoubleScroll#readme In particular, I copied this file from the repository to MyApp/static/admin/js/ jquery.doubleScroll.js The file looks like this: /* * @name DoubleScroll * @desc displays scroll bar on top and on the bottom of the div * @requires jQuery * * @author Pawel Suwala - http://suwala.eu/ * @author Antoine Vianey - http://www.astek.fr/ * @version 0.5 (11-11-2015) * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Usage: * https://github.com/avianey/jqDoubleScroll */ (function( $ ) { jQuery.fn.doubleScroll = function(userOptions) { // Default options var options = { contentElement: undefined, // Widest element, if not specified first child element will be used scrollCss: { 'overflow-x': 'auto', 'overflow-y': 'hidden', 'height': '20px' }, contentCss: { 'overflow-x': 'auto', 'overflow-y': 'hidden' }, onlyIfScroll: true, // top scrollbar is not … -
How to estabalish ManyToMany relationship on instantiation of object through generic CreateView?
So I have two models. Deck and Card. When the user creates card it should be tied to a deck, in a ManyToMany relationship. The card is created through the Generic Django create view, and I can't crack how I can assign the card to a deck, in this context. Any ideas on how I might solve this? My CreateView class CardCreateView(LoginRequiredMixin, CreateView): model = Card fields = ['question', 'answer'] def form_valid(self, form): form.instance.creator = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('spaced_repitition-home') def assign_card(self, deck_id): #It's largely this part where I don't understand that it doesn't work card = self.get_object() deck = get_object_or_404(Deck, pk=deck_id) card.decks.add(deck) card.save() Template that sends user to form (passes on deck_id) {% for deck in decks reversed %} <a href="{% url 'card-create' deck_id=deck.id %}"> <p> Add Card </> {% endfor %} Form Template {% extends "spaced_repitition/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class=form-group> <legend class="borders-bottom mb-4"> Create Card </legend> {{ form|crispy }} <div class=form-group> <button class= "btn btn-outline-info" type="submit"> Create </button> </div> </fieldset> </form> {% endblock content %} Models class Deck(models.Model): title = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) creator = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField(max_length=200, blank=True) … -
RenderItems is not defined no-undef inside return
Hello Guys am new in reactjs and Iam trying to get response data object to be able to display on the webapp for the users to see instead of them inspecting the page and going to network/console to see the file upload error response of name= 'title' so I decided to use the function below to be able to give me the data response and I keep on getting this error 'renderItems is not defined' no-undef Heres the sample code: import React from "react"; import PropTypes from "prop-types"; import axios from 'axios' import { Card,} from "shards-react"; class Uploaddatastore extends React.Component { constructor(props) { super(props); this.state = { UploadNotification: [] } } componentDidMount(){ let notificationComponent = this; axios.get("http://127.0.0:8000/uploads/file_upload/") .then(function (response) { console.log(response); console.log(response.data); notificationComponent.setState({ UploadNotification: response.data.items }); }) .catch(function (error) { console.log(error); }); } render() { if (this.state.UploadNotification.length) { let renderItems = this.state.UploadNotification.map(function(item, i) { return <li key={i}>{item.title}</li> }); } return ( <div> <span className="text-danger"> {renderItems} </span> </div> ); } }; export default Uploaddatastore; -
Not able to serialize a model object in django signals
I have a Task model. After saving the task I want to send a FCM to a device. So I decided to use django signals. Here's the code for it: The model: class Task(models.Model): id = models.AutoField(primary_key=True) issuer = models.ForeignKey(EndUser, on_delete=models.CASCADE, related_name='history') assignee = models.ForeignKey(Mechanic, on_delete=models.CASCADE, related_name='history') vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, related_name='history') service = models.ForeignKey(Service, on_delete=models.CASCADE) status = models.CharField('Task Status', choices=TASK_STATUS, default=TASK_STATUS[0][0], max_length=64) payment_status = models.CharField('Payment Status', choices=PAYMENT_STATUS, default=PAYMENT_STATUS[0][0], max_length=64) def __str__(self): return "{}-{}-{}".format(self.service, self.issuer, self.assignee) post_save.connect(send_mechanic_notification, sender=Task) The signal function: def send_mechanic_notification(sender, instance, created, **kwargs): if created: instance.assignee.device.send_message( title='New Task Available!', body='Hey!! A new task is available for you', data={ "event": "new_task", "data": instance } ) Now, obviously this won't work because instance is a model object and needs to be serialized. So I tried using a serializer that I have defined. But this was causing circular dependency. I don't want to user model_to_dict because it doesn't serialize the nested fields, and serializing the nested fields is a requirement. How can I solve this problem? -
Django 2.2 how do i list objects with a many to many in a template?
Hi all, I have seen similar questions to this. However the answers don't print anything out in my code. Can someone help with the below? I am trying to list some products and should display the appropriate text, depending on whether they are in the cart. "In cart", "add to cart". The models I have are: class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) image = models.ImageField(upload_to='products/', null=True, blank=True) featured = models.BooleanField(default=False) quantity = models.IntegerField(default=0) active = models.BooleanField(default=True) is_digital = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class CartItem(models.Model): product = models.ForeignKey(Product, default=None, null=True, blank=True, on_delete=models.CASCADE) quantity = models.IntegerField(default=None, null=True) price_of_item = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) session_id = models.CharField(max_length=120, default=0, null=True, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) def __str__(self): return str(self.id) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) cart_items = models.ManyToManyField(CartItem, default=None, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) In list.html I list all the products available: {% if product_list %} <div class="row"> {% for product in product_list %} <div class='col-sm-12 col-md-4 col-lg-4 my-2'> {% include 'products/snippets/card.html' with product_obj=product %} <br> </div> {% endfor %} </div> … -
CeleryD seems to ignore concurrency arguemtn
I've recently upgraded my Django project to Celery 4.4.6 and things aren't going well. My current number one problem is the concurrency of tasks. Because the tasks lock database tables and some are very memory intensive, there's no chance to run eight tasks at the same time. However, that is what celery is set on doing. Previously I was able to run just two tasks at the same time. The worker is daemonised and only one worker is live (one node). I set the concurrency to two. Here's my /etc/default/celeryd: # most people will only start one node: CELERYD_NODES="worker1" # but you can also start multiple and configure settings # for each in CELERYD_OPTS #CELERYD_NODES="worker1 worker2 worker3" # alternatively, you can specify the number of nodes to start: #CELERYD_NODES=3 # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/ubuntu/dev/bin/python -m celery" #CELERY_BIN="/virtualenvs/def/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="match2" # or fully qualified: #CELERY_APP="proj.tasks:app" # Where to chdir at start. export DJANGO_SETTINGS_MODULE="match2.settings" CELERYD_CHDIR="/home/ubuntu/dev/match2/match2" # Extra command-line arguments to the worker CELERYD_OPTS="--concurrency=2" # Configure node-specific settings by appending node name to arguments: #CELERYD_OPTS="--time-limit=300 -c 8 -c:worker2 4 -c:worker3 2 -Ofair:worker1" # … -
Auto Increment field with starting value in Django
I am creating a model given below. I want the student id to start from 100000. class StudentLogin(models.Model): student_id = models.AutoField(min_value = 100000) email = models.EmailField(max_length=200) password = models.CharField(max_length=255) I am getting the following error if I use min_value TypeError: __init__() got an unexpected keyword argument 'min_value' -
UserProfileInfoForm' object is not callable
''' views.py from django.shortcuts import render from practise.forms import UserForm, UserProfileInfoForm def index(request): return render(request, 'index.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'registration.html', {'user_form': user_form, 'profile_form': profile_form, 'resigtered': registered}) ''' '''' error Internal Server Error: /index/register/ Traceback (most recent call last): File "C:\Users\Faris\PycharmProjects\djangoProject4\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Faris\PycharmProjects\djangoProject4\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Faris\PycharmProjects\djangoProject4\practise\views.py", line 22, in register profile = profile_form(commit=False) TypeError: 'UserProfileInfoForm' object is not callable [19/Aug/2020 21:05:57] "POST /index/register/ HTTP/1.1" 500 68871 '''' -
Django Form- Password Validation
I am new to Django just started learning it yesterday. I am trying to create a register form. I know there is inbuilt django register system. But i am trying to it myself. This is my Views.py- def register(request): if request.user.is_authenticated: return render(request, 'users.html', {}) else: if (request.method=='POST'): form=Register(request.POST) if form.is_valid(): form.save() return render(request,'home.html',{}) else: return render(request,'register.html', {}) Template- <form method="post"> {% csrf_token %} <input type="text" name="username" placeholder="Username" required><br> <input type="email" name="username" placeholder="Email" required><br> <input type="password" placeholder="Password" name="password" required><br> <input type="password" placeholder="Password" name="cpassword" required><br> <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="female">Female<br> <input type="submit"> form.py class Register(forms.ModelForm): class Meta: model = Users fields = ["username", "email", "password","gender"] But since there is no confirm password field in form.py. It does not past form.is_valid() statement. I know this may be a stupid. But just can't find a way to do this. -
How to test which EMAIL credentials were used in tests
I am building an application that sends email through multiple email servers. To achieve this, I created my own settings that allow for multiple email server configurations. Now I am testing and I want to ensure the method is inserting the correct credentials. I looked at the django.core.mail and there does not appear to be anything there. Is there a way to test which credentials were used when testing email sending? -
Django channels, time a message in a websocket
I want to implement a WebSocket which execute a queryset every 120 seconds and returns a response in according to some logic (already exsits) class CarConsumer(JsonWebsocketConsumer): def connect(self): # Manually adding a user for now, later from the url route. self.user_name = '1' self.user_group_name = 'user_%s' % self.user_name self.group = [self.user_group_name, self.channel_name] # Join user group async_to_sync(self.channel_layer.group_add)( self.group[0], self.group[1] ) # TODO: Once working, add Auth # accept connection self.accept() def car(self): result = self.check_events() # Get updated car status self.channel_layer.send( self.farm_group_name, # send result to group {'type': 'check_events', 'message': result } ) def check_events(self): Car.objects.filter() # rest of logic cut dows due to length. So, this code connects when using: const ws = new WebSocket("ws://127.0.0.1:8000/ws/car_online/connect/"); a connection is established, but I can't seem to be able to send a proper message, and other then that, I want the check_events method (the logic) to run every 120 seconds, how can I implement this behavior? The result of the check events method is always a dictionary if it changes something. -
Django graphql-jwt refresh token - Invalid object name 'refresh_token_refreshtoken'
I used to work on this application on a different machine. I fetch the app from Git installed all dependencies and migrated my database (I am using MS Sql Server). when i tried to authenticate i got this error: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'refresh_token_refreshtoken'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") I don't know what happened wrong. and if this object should be created with the migrations. -
Django models: how to get an model object in my views
So I have this models class ThreadManager(models.Manager): def by_user(self, user): qlookup = Q(first=user) | Q(second=user) qlookup2 = Q(first=user) & Q(second=user) qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct() return qs def get_or_new(self, user, other_username): # get_or_create username = user.username if username == other_username: return None qlookup1 = Q(first__username=username) & Q(second__username=other_username) qlookup2 = Q(first__username=other_username) & Q(second__username=username) qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct() if qs.count() == 1: return qs.first(), False elif qs.count() > 1: return qs.order_by('timestamp').first(), False else: Klass = user.__class__ user2 = Klass.objects.get(username=other_username) if user != user2: obj = self.model( first=user, second=user2 ) obj.save() return obj, True return None, False class Thread(models.Model): first = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first') second = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second') updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) thread_notification = models.IntegerField(default=0) objects = ThreadManager() in my model Thread I want to get the object thread_notifications, so I make my views like this def new_notification_thread(request): thread_notifier = Thread.objects.filter(pk=1) thread_notifier.thread_notification += 1 thread_notifier.save() return JsonResponse(serializers.serialize('json', [thread_notifier]), safe=False) The problem is that when I run my code I get Thread matching query does not exist. does anybody know what is going on? -
FileNotFoundError at /analyze/info/ [Errno 2] No such file or directory: '/media/test2_SjHB3FP.jpg'
I am new to Django. I am trying to upload the image and use that image in a view.py function as well show in index.html. Below are the steps I performed but getting error as "No such file or directory". I feel like I am doing some mistake to the path which I have provided in it, But I'm not sure where I am doing wrong. #Settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' after creating this MEDIA_URL I pass this into the urls.py of the root folder: #root\urls.py urlpatterns = [ path('admin/', admin.site.urls), path('xxxxx/', include('xxxx.urls')) ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) then i created application\model.py: #application\model.py from django.db import models class history(models.Model): url = models.CharField(max_length=200) data = models.CharField(max_length=2500) now application\urls.py: #application\urls.py urlpatterns = [ path('', views.index, name='index'), path('info/', views.info, name='info'), path('history/', views.getHistory, name='history'), ] Now this is my application\views.py: def info(request): os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'bd5f7e5a.json' client = vision.ImageAnnotatorClient() myfile = request.FILES['pic'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) file_name = fs.url(filename) with io.open(file_name, 'rb') as image_file: # at this line I am getting the error that no such file found #********function goes here ********* return render(request, 'results.html', {"labels":doctext, 'image': file_name}) Now check my index.html file: <body > <form action='/analyze/info/' method='post' class="form" enctype="multipart/form-data"> {% csrf_token %} … -
how can I filter the difference between the two models? using django
I have 2 models, Product and ProductRelatedGroupAndProduct , the Product have 5 data, [chicken, okra, ampalaya, cabbage, carrots] and the ProductRelatedGroupAndProduct have [chicken, okra, cabbage] how do i get the remaining data in Product that dont have in ProductRelatedGroupAndProduct ? the choosen product is ProductRelatedGroupAndProduct and the list of product is Product I just want that the data displayed on the choosen product should no longer be visible in the product list. so far this is my views.py def searchrelatedproduct(request): id = request.GET.get('relatedproductID') products = Product.objects.all() relatedproduct = ProductRelatedGroupAndProduct.objects.filter(productrelatedgroup = id) return render(request, "customAdmin/relatedproduct.html",{"products":products,"relatedproduct":relatedproduct}) this is my html <div class="container"> <form method="POST" action="/GroupOfProduct/" enctype="multipart/form-data">{% csrf_token %} <h2>Product </h2> <div class="form-group"> <br> <label for="sel2">List Of Products</label> <select multiple class="form-control" id="sel2" name="product"> {% for product in products %} <option>{{product.product}}</option> {% endfor %} </select> </div> <input type="submit" style="float:right;"> </form> </div> <div class="container"> <h2>Choosen Product</h2> <form method="POST" action="/UpdateGroupOfProduct/" enctype="multipart/form-data">{% csrf_token %} <input type="submit" style="float:right;"> <div class="form-group"> <br> <label for="sel2">List Of Choosen Products</label> <select multiple class="form-control" id="sel2" name="relatedproduct"> {% for product in relatedproduct %} <option value="{{ product.id }}">{{product.product}}</option> {% endfor %} </select> </div> </form> </div> -
Elasticsearch document fields type index automatically changes
I'm working on a project containing django, elasticsearch and django-elasticsearch-dsl. I'm collecting a quite large ammount of data and saving it to postgres and indexing it to elasticsearch, via django-elasticsearch-dsl. Im bumping into a problem I dont understant, nor do I have any further hints what happens: Relevant part of Django's models.py file: class LinkDenorm(BaseModel): ... link = CharField(null=True, max_length=2710, db_index=True) link_expanded = TextField(null=True, db_index=True) title = TextField(null=True, db_index=True) text = TextField(null=True) ... Relevant part of django-elasticsearch-dsl documents.py file: @registry.register_document class LinkDenorm(Document): link_expanded = fields.KeywordField(attr='link_expanded') class Index: name = 'denorms_v10' class Django: model = models.LinkDenorm fields = [ ... 'link', 'title', 'text', ... ] After data is successfully indexed, I verify that the index is containing the correct fields: curl -X GET -u <myuser>:<mypasswd> "http://<my-hostname>/denorms_v10/?pretty" { "denorms_v10" : { "mappings" : { "properties" : { ... "link" : { "type" : "text" }, "title" : { "type" : "text" }, "text" : { "type" : "text" } "link_expanded" : { "type" : "keyword" }, ... } } } } After a certain ammount of time (sometimes weeks, sometimes days) the index fields are changed. Executing the same CURL lookup as before gives me: curl -X GET -u <myuser>:<mypasswd> "http://<my-hostname>/denorms_v10/?pretty" { … -
Django dynamic form for call of roll
I need to create a form with django to check if students are prensent or not. I can't use the 'normal' way to create a form because django want a form model implemented with every fields composing the form. I can't do this cause i don't know the number of students in a class. how can i create a dynamic form who don't care about the number of students ? at the moemnt i created a form in the template with a for to showthe list of students with each checkbox <form method="post"> {% csrf_token %} Date : <input id="date" type="date" class="mt-3 mb-3"> <br> {% for student in student_list %} <input type="checkbox" id="student{{forloop.counter}}" name="student{{forloop.counter}}"> <label for="student{{forloop.counter}}">{{student.first_name }} {{student.last_name}}</label> <br> {% endfor %} <button class="btn btn-outline-primary mr-4"><a href="/lycee/">Cancel</a></button> <button type="submit" class="btn btn-success radius d-flex">Submit</button> </form> -
Inline css image reference in Django template
I passed context_object_name = 'project' in template and I need this: <div style="background-image: url( {{ project.thumbnail.url}} )"></div> but above line doesn't work. However, <img src="{{ project.thumbnail.url }}" alt="thumb" /> works fine. What is the solution? Thank you in advance