Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework serializer create() doesn't get triggered
I have the following serializer class MyModelSerializer(serializers.ModelSerializer): user = UserSerializer() def create(self, validated_data): print("TEST") MyModel, created = MyModel.objects.get_or_create(**validated_data) return MyModel class Meta: model = MyModel fields = ('pk', 'title', 'user', 'movie', 'timestamp', 'text',) and the following viewset: class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer When I make an POST request to the endpoint corresponding to specified viewset, the create() method does absolutely nothing. I tried to print out in console TEST as you can see, but nothing. Does anyone have an idea about this strange behavior? Thanks in advace! -
What is the fastest way to send files of any size and format?
I build web application with Angular 6 frontend, Django 1.11 backend and Hadoop 3.1. I need to send files of any size and format in the fastest possible way. My method in Django looks line shown below. Everything seems to be working fine with small files in different formats. However very often when I try to upload larger files I get the error shown at the bottom. Can you recommend the way of sending files of all formats and sizes in the fastest possible way? Thanks in advance. def post(self, request): key = request.META.get('HTTP_AUTHORIZATION').split()[1] user_id = Token.objects.get(key=key).user_id user_name = User.objects.get(id=user_id).username upload_file(request.FILES['file'], user_name) return Response(status=status.HTTP_201_CREATED) def upload_file(file, user_name): response = requests.put(url + ':9870/webhdfs/v1/user/' + str(user_name) + '/' + str(file) + '?op=CREATE&user.name=myuser&createflag=&createparent=true&overwrite=false' , data=file, headers={'content-type':'application/octet-stream'}) return response ERROR: django_1 | Internal Server Error: /cloud/ django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen django_1 | chunked=chunked) django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request django_1 | conn.request(method, url, **httplib_request_kw) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1239, in request django_1 | self._send_request(method, url, body, headers, encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1285, in _send_request django_1 | self.endheaders(body, encode_chunked=encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1234, in endheaders django_1 | … -
Windows hosted Django application Suddenly stopped working
I have an django web application which having 2 applications. One application renders the page by accessing the server_url and other one is accessed by passing server_url/applicaion_name. I used Django 1.8.4 and python 2.7.10 for the development and hosted in iis 8.0. The application was working fine for pass 2+ months and out of the blue, application started throwing. HTTP Error 500.0 - Internal Server Error c:\Python27\python.exe - The FastCGI process exited unexpectedly Here comes the tricky part. Error is coming only while accessing the server URl(renders home page previously) and app hosted in erver_url/applicaion_name is still working fine. Any suggestion would be really helpful. -
How to get extra parameters in a Django Rest Framework ViewSet
I have to implement an end-point with Django Rest Framework that receives extra parameters this way: GET .../hotels_in_period/?check_in=2018-09-30&check_out=2018-10-10 The end-point should receive both parameters check-in and check-out, but I don't know how to get them in the list method of the viewset. I thought they would be available as request.data, but they are not. I'll appreciate any help. -
Authentication/Authorization for default resolvers
I read the description on how to use @login_required and other decorators with resolvers. However, if one is not using explicit resolvers (instead using default ones), how can one enforce similar access controls? In my case, I am using graphene with the Django User model. I have the following: class UserNode(DjangoObjectType): class Meta: model = User filter_fields = ['first_name', 'last_name', 'id', 'email'] interfaces = (Node, ) class Query(object): userNode = relay.Node.Field(UserNode) all_users = DjangoConnectionField(UserNode) If I explicitly define a 'resolve_all_users' method and use the @login_required decorator on it, it works fine. But this (and other objects) in my schema are relying on default resolvers. How can I protect them without having to define resolvers explicitly? I admit to being a novice in the use of graphene/graphql......and any help pointing me in the right direction is much appreciated. Source: https://github.com/flavors/django-graphql-jwt/issues/36 -
How do I render context variables in DjangoCMS text plugins?
I'm using DjangoCMS to allow users to dynamically edit content on pages. This content needs access to context variables to properly display it on the page. For example, suppose I have a header that says "{{user.name}} has invited you to join our community." I'd like admin users of our site to be able to edit this header to say something like "Your friend, {{user.name}}, would like you to join our community." Is there a way to interpolate context variables within PlaceHolderFields in DjangoCMS? Do I have to create a new CMSPlugin? If so, how would I get started with that? -
Django Models Clean Method for Admin and Staff User
I have a task and i need to write a solution to this problem. Have 2 fields parking_on and parking_off. If the user is staffuser then parking_off date has to be the same as parking_on and if the user is admin, then parking_off can be on a different date than parking_on. class Parking(models.Model): parking_on = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege data cand doresti sa vii in office',) parking_off = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege Data Plecarii') Have tried with this, but it doesn't catch the error, it simply save to the database: def clean_parkingoff(self, request): if not request.user.is_superuser and self.parking_off !=self.parking_on: raise ValidationError( {'parking_off': _('You cant book for a future date!')}) -
Django Rest Framework Pass extra arguments to Serializer
I'm trying to figure out how to pass extra parameters to a serializer. My case is this: class ActivityDataHours(generics.RetrieveUpdateAPIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): pa = ProjectActivity.objects.values('project_code').distinct() if request.GET.get('activityCode') is not None: is_code_filter = False else: is_code_filter = True return Response(ActivityDataHoursSerializer(pa, many=True, context={'is_code_filter': is_code_filter}).data) class ActivityDataHoursSerializer(serializers.ModelSerializer): activity_hours = serializers.SerializerMethodField() @staticmethod def get_activity_hours(self, project_activity): is_code_filter = self.context.get("is_code_filter") wh = WorkedHours.objects.values('project_code') return wh class Meta: model = Project fields = ['activity_hours'] answers already available: Pass extra arguments to Serializer Class in Django Rest Framework But I can't understand how take the self parameters. The error that appears to me is this: TypeError: get_activity_hours () missing 1 positional argument required: 'project_activity' -
The best approach to adding images in an article in Django
It's a quite typical task to add several images with captions in arbitrary position within an article; what's the best way to do so in Django? Let's assume I have two models: class Article(models.Model): heading = models.CharField(max_length=350) text = models.TextField() class ImageModel(models.Model): image = models.ImageField( upload_to = 'static/images/', max_length=300) img_alt = models.CharField(max_length=550, blank = True) Now, I'd like to add a couple of images with captions in an article. Its text is stored with HTML formatting: <p>Paragraph 1</p> [Image 1 + caption] <p>Paragraph 2</p> [Image 2 + caption] <p>Paragraph 3.</p> <...> What should I do to accomplish this? I guess it's necessary to create a custom tag, and make a tool for inserting this tag in a TextField with help of JS. While inserting, the id of a selected instance of ImageModel has to be passed somehow into the tag. And finally, this custom tag should be processed when rendering a template. Am I right? Is there any easier and more straightforward approach? (I use Django 2.0.) -
Django Modelchoicefield and Form not valid
Problem: Currently my form is not valid, here are my codes. Forms.py: The data is from Post model, which include 5 columns, I would like to select variables in column "symbol". Is this the right way to select that column? class My_Form(forms.Form): coinname1 = forms.ModelChoiceField(queryset=Post.objects.all()) Views.py: Currently when I hit submit, it just show a message error, and im not sure why it's not valid. def about(request): if request.method == 'POST': form = My_Form(request.POST) if form.is_valid(): coinname1 = form.cleaned_data['coinname1'] return render(request, 'blog/testing.html'{'coinname1':coinname1}) else: messages.error(request, "Error") else: form = My_Form() return render(request, 'blog/testing.html', {'form':form} ) Template: In my template, I use choice.symbol because i want to select names in a column called symbol. Is this the right way? Once they hit submit, it should say "The name is USD" on the same page, for example. <div class="container"> <form width="600px" action="." method="post" > {%csrf_token%} <div class="row align-items-start"> <select class="form-control" id="coinname1" name ="coinname1"> {% for choice in form.coinname1.field.queryset %} <option value="{{choice.symbol}}">{{choice.symbol}}</option> {% endfor%} </select> </div> <button type="submit">Submit</button> </form> <div class="text2 offset-md-3"> <h1> The name is <u>{{coinname1}}</u> </h1> </div> -
Is it possible to limit accessing posts to its own writer?
In my Django admin, I have a column, created_by, which is for who made a post. I have many people who can access Django admin to make posts. The problem is that it is possible for them to edit each other's posts right now. I want them to be able to edit only their each own posts, not others' posts. Is there anyway to limit access permission to a specific user in Django admin? Also, here's my codes for admin.py and models.py. admin.py @admin.register(Store) class StoreAdmin(SummernoteModelAdmin): summernote_fields = '__all__' formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': '91'})}, } list_display = ('id', 'status', 'businessName', 'typ', 'author', 'updated_by', 'created_by', 'updated_at', 'created_at') list_filter = ('businessName',) search_fields = ('businessName',) def save_model(self, request, obj, form, change): # adding the entry for the first time if not change: obj.created_by = request.user # updating already existing record else: obj.updated_by = request.user obj.save() models.py class Store(TimeStampedModel): ... created_by = ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='stores_of_created_by', null=True, blank=True) updated_by = ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='stores_of_updated_by', null=True, blank=True) -
How to get all the objects of a class in one variable with Django 2.1 (Python 3.7)
variable = myclass.objects.all() Hello, this line of code used to work with python 2.9 but it doesn't with the newest version I need to get all the object of my instance in one variable can any one help please ? -
Django Admin Customise Save Function for Admin to be different than regular Staff User
I want to run a customised save function for an admin that has to be different from the regular one. The reason is that I have made hidden a field from my models (parking_off). I am doing a parking app, and managers want a field to be hidden for staff users, therefore they somehow tweaked my entire code. How i can make this save function to run only for admins? The parking_off field is visible only for admins. def save(self): list = [] d = self.parking_on while d <= self.parking_off: list.append( Parking(user=self.user, email=self.email, parking_on=d, parking_off=d, location=self.location ) ) d = d + timedelta(days=1) Parking.objects.bulk_create(list) Please find bellow my models: from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime, timedelta, time from django.core.exceptions import NON_FIELD_ERRORS today = datetime.now().date() tomorrow = today + timedelta(1) now = datetime.now() l = now.hour m = int(now.strftime("%H")) class ParkingManager(models.Manager): def active(self, *args, **kwargs): return super(ParkingManager, self).filter(draft=False).filter(parking_on__lte=datetime.now()) class Parking(models.Model): PARKING_PLOT = ( ('P1', 'Parking #1'),('P2', 'Parking #2'), ('P3', 'Parking #3'), ('P4', 'Parking #4'),('P5', 'Parking #5'), ('P6', 'Parking #5'), ('P7', 'Parking #7'),('P8', 'Parking #8'), ('P9', 'Parking #9'), ('P10', 'Parking #10'),('P11', 'Parking #11'), ('P12', 'Parking #12'), … -
Strange behavior on Bootstrap 4 drop-down by bootstrap.min.js
I have a problem with bootstrap drop-down menus I have this template: {% extends 'damage/base.html' %} {% load widget_tweaks %} {% load static %} {% block title %} {{ general.deya_name }} - BΛΑΒΕΣ {% endblock %} {% block body %} <script src="{% static 'damage/bootstrap-4.1.1-dist/js/bootstrap.min.js' %}"></script> <script src="{% static 'damage\gijgo-combined-1.9.6\js\gijgo.min.js' %}" type="text/javascript"></script> <script src="{% static 'damage\gijgo-combined-1.9.6\js\messages\messages.el-el.js' %}" type="text/javascript"></script> <link href="{% static 'damage\gijgo-combined-1.9.6\css\gijgo.min.css' %}" rel="stylesheet" type="text/css" /> <script src="{% static 'js\moment.js' %}" type="text/javascript"></script> <div class="container"> <h1 style="font-family: Calibri; align-content: center" align="center" > KΡΙΤΗΡΙΑ ΠΡΟΒΟΛΗΣ ΜΥΝΗΜΑΤΩΝ </h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group row"> <div class="col-2" > <label for = "d1" >Από Ημερομηνία </label> </div> <div class="col-2"> <input id="fromdate" width="170" class="form-control" name="fromdate" /> <script> $('#fromdate').datepicker({ locale: 'el-el', format: 'dd/mm/yyyy', uiLibrary: 'bootstrap4', value: new moment().format("DD/MM/YYYY") }); </script> </div> <div class="col-3" align="right"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color: white; width: 300px"> Επιλογή Περιόδου Ημερομηνιών </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="dateselected"> <li><a class="dropdown-item" style="color: #062c33; width: 300px">Σήμερα</a></li> <li><a class="dropdown-item" href="#" style="color: #8a6d3b;">Τελευταία Εβδομάδα</a></li> <li><a class="dropdown-item" href="#" style="color: #721c24;">15-ήμερο</a></li> <li><a class="dropdown-item" href="#" style="color: #002a80;">Μήνας</a></li> <li><a class="dropdown-item" href="#" style="color: #a41515;">3-μηνο</a></li> <li><a class="dropdown-item" href="#" style="color: #333333;">6-Μηνο</a></li> <li><a class="dropdown-item" href="#" style="color: #721c24;">Ετος</a></li> </ul> </div> </div> </div> <div class="form-group row"> <div class="col-2" > <label>Έως … -
Check if string exists in Many-to-one relationships
I try to code a simple Shopping-Cart in Django and have the following models: class Product(models.Model): name = models.CharField(max_length=256) serial = models.CharField(max_length=128) def __str__(self): return self.name class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) class CartEntry(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return str(self.id) How would i check if a CartEntry already exists for the Product, so i can increment the quantity +1, when it already exists or create a CartEntry when it does not exists? I think about something like this: def cart_update(request, id): product_id = id my_cart_id, my_cart = Cart.objects.get_or_create(user=request.user) product_obj = Product.objects.get(id=product_id) product_quantity = "1" for item in CartEntry.objects.filter(cart=my_cart_id): #check all products in CartEntry if it already exists if not item.product.exists(): #Product does not exists yet - creating a CartEntry CartEntry.objects.create(cart=my_cart_id, product=product_obj, quantity=product_quantity) else: #Product does exists - incrementing the quantity return HttpResponseRedirect(reverse('list-products')) -
Django form with ModelMultipleChoiceField rendered empty
I have trouble setting up a form with a ModelMultipleChoiceField where the queryset depends on the user. My Goal is to implement an export function. My View looks like this: class ExportView(FormView): template_name = 'ExportTemplate.html' def get(self, request, *args, **kwargs): self.form_class = ExportForm(user = request.user) return render(request, self.template_name, {'form': self.form_class}) def get_success_url(self): return '/addrbook/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. return super().form_valid(form) form: class ExportForm(forms.Form): def __init__(self, user, *args, **kwargs): usersContacts = ContactManager().getAllUsersContacts() self.contactList = forms.ModelMultipleChoiceField(queryset = usersContacts[str(user)]) print(usersContacts[str(user)]) super(ExportForm, self).__init__(*args, **kwargs) I verified that the queryset is not empty, it contains a list of model objects. My template looks like this: <form method="post">{% csrf_token %} {{ form }} <input type="submit"> the only thing that get's rendered is the submit button. Another thing that left me completely unsure of python basics is that this code: class ExportForm(forms.Form): contactList = forms.ModelMultipleChoiceField(queryset = []) def __init__(self, user, *args, **kwargs): usersContacts = ContactManager().getAllUsersContacts() self.contactList.queryset = usersContacts[str(user)] print(usersContacts[str(user)]) super(ExportForm, self).__init__(*args, **kwargs) returned the runtime error: 'ExportForm' object has no attribute 'contactList' How is it possible? the contactList member is part of the ExportForm class definition and 'self' should point … -
Django - how to correctly upload and handle a file?
I have the following model of an apk, the package_name and sdk_version will be taken by parsing the apk file which the user will upload. I also need to save the path of the uploaded file in my model, that's why I used FilePathField, however I'm not sure it's the correct way to handle the task. I saw some examples where FileField was used, and it got me confused, when do I use which? Another point to make, since a path is just a string, I can save it as Charfield, can't I? class Apk(models.Model): package_name = models.CharField(max_length=45, unique=True) sdk_version = models.CharField(max_length=45, unique=True) apk_file = models.FilePathField() To upload the file I used this guide. views.py: def upload_apk(request): handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) return HttpResponse("Upload Successful") def handle_uploaded_file(file, filename): if not os.path.exists('policies/upload/'): os.mkdir('policies/upload/') with open('policies/upload/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) apk_path = "/policies/upload/" + filename apkf = APK(apk_path) package_name = apkf.get_package() sdk_version = apkf.get_androidversion_name() template.html: <form id="uploadApkForm" action="{{ request.build_absolute_uri }}uploadApk/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="input-element" style="border:1px solid black; background:white; padding:2px"> <input type="file" name="file" style="width:100%" required> </div> <div style="width:100%;"> <div style="position: absolute; left: 50%; bottom: 0px; transform: translate(-50%, -50%); margin: 0 auto;"> <input id="uploadBtn" type="submit" value="Ok" class="btn btn-primary" … -
Django: Unique order_reference
I have to create a unique order_reference field. I read that I should use UUID for that. Can you recommend that? And is that here the right approach to it? (I found this snippet in another project) uuid.UUID(bytes=base64.urlsafe_b64decode('%s==‘ % base64_uuid)) I don't understand what urlsafe_b64decode is doing. -
Django falis when invalid values enter for dates
Im using two date fields in my model as follows. class Booking(models.Model): checkin_date = models.DateField() checkout_date = models.DateField() ... I use model form in my create view. I override the forms' clean() method to do conditional validation between fields. class BookingForm(forms.ModelForm): class Meta: model = Booking def clean(self): cleaned_data = super(BookingForm, self).clean() checkin_date = self.cleaned_data['checkin_date'] # fail here checkout_date = self.cleaned_data['checkout_date'] # fail here self.validate_dates(checkin_date, checkout_date) When I enter invalid values (such as 2018-09-31) for either dates it just fail and stack trace is printed. Stack Trace: File "/home/indikau/workspace/projects/src/booking/forms.py" in clean 67. checkout_date = self.cleaned_data['checkout_date'] Exception Type: KeyError at /booking/add/ Exception Value: 'checkout_date' 1) Is this the behavior for all form field validations and occurring only if clean() method is overridden? 2) How to overcome the issue without totally failing? -
Error when deploying existing django app on PythonAnywhere
I'm desperate. I'm trying to deploy an existing django app on PythonAnywhere, and I stucked at the popular error: ModuleNotFoundError: No module named 'sw.settings'. My WSGI (at var/www): import os import sys path = '/home/SamperMan/sw' # manage.py is in that folder if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'sw.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I've read DebuggingImportError page and everything here works fine: (mysite-virtualenv) 14:14 ~/sw (master)$ python -i /var/www/samperman_pythonanywhere_com_wsgi.py >>> import sw.settings >>> sw.settings.BASE_DIR '/home/SamperMan/sw' >>> I've configured web app settings (set a Source code and VirtualEnv settings), installed django on the new virtualenv. I really don't know where could I miss something? What mistake can it be? -
Django & css : Apply Css on a django form field
I have the modelForm that contains one field : class sarlform(forms.ModelForm): denomination_social=forms.CharField(widget=forms.TextInput(attrs={'onkeyup':'this.value=this.value.toUpperCase()'}),required = False) I need to apply a css code on this field, to do so , I added 'class':'test' to my field attrs . class sarlform(forms.ModelForm): denomination_social=forms.CharField(widget=forms.TextInput(attrs={'class':'test','onkeyup':'this.value=this.value.toUpperCase()'}),required = False) test is a css class defined as follow : .test{ background-color: #4CAF50; } However Nothing happens on my field, Css doesn't work , and I dont know why? THANK YOU IN ADVANCE -
Select a choice and do not allow to select it again in django model
I'm working with Django choices, and what I want to do is that, if you select one choice, django shouldn't allow you to choose this choice once again, so in my form I only want to select one instrument for each time, and I really don't know how to do that. Feel free to ask anything you want, I know that maybe I didn't explain my problem correctly. Here's my django model: class Cancion(models.Model): nota_35='35' nota_36='36' nota_37='37' nota_38='38' nota_39='39' nota_40='40' nota_41='41' nota_42='42' nota_43='43' nota_44='44' nota_45='45' nota_46='46' nota_47='47' nota_48='48' nota_49='49' nota_50='50' nota_51='51' nota_52='52' nota_53='53' nota_54='54' nota_55='55' nota_56='56' nota_57='57' nota_58='58' nota_59='59' nota_60='60' nota_61='61' nota_62='62' nota_63='63' nota_64='64' nota_65='65' nota_66='66' nota_67='67' nota_68='68' nota_69='69' nota_70='70' nota_71='71' nota_72='72' nota_73='73' nota_74='74' nota_75='75' nota_76='76' nota_77='77' nota_78='78' nota_79='79' nota_80='80' nota_81='81' notas=((nota_35,'Acoustic Bass Drum'),(nota_36,'Bass Drum 1'),(nota_37,'Side Stick'),(nota_38,'Acoustic Snare'),(nota_39,'Hand Clap'), (nota_40,'Electric Snare'),(nota_41,'Low Floor Tom'),(nota_42,'Closed Hi Hat'),(nota_43,'High Floor Tom'),(nota_44,'Pedal Hi-Hat'), (nota_45,'Low Tom'),(nota_46,'Open Hi-Hat'),(nota_47,'Low-Mid Tom'),(nota_48,'Hi-Mid Tom'),(nota_49,'Crash Cymbal 1'),(nota_50,'High Tom'), (nota_51,'Ride Cymbal 1'),(nota_52,'Chinese Cymbal'),(nota_53,'Ride Bell'),(nota_54,'Tambourine'),(nota_55,'Splash Cymbal'), (nota_56,'Cowbell'),(nota_57,'Crash Cymbal 2'),(nota_58,'Vibraslap'),(nota_59,'Ride Cymbal 2'),(nota_60,'Hi Bongo'),(nota_61,'Low Bongo'), (nota_62,'Mute Hi Conga'),(nota_63,'Open Hi Conga'),(nota_64,'Low Conga'),(nota_65,'High Timbale'),(nota_66,'Low Timbale'),(nota_67,'High Agogo'), (nota_68,'Low Agogo'),(nota_69,'Cabasa'),(nota_70,'Maracas'),(nota_71,'Short Whistle'),(nota_72,'Long Whistle'),(nota_73,'Short Guiro'), (nota_74,'Long Guiro'),(nota_75,'Claves'),(nota_76,'Hi Wood Block'),(nota_77,'Low Wood Block'),(nota_78,'Mute Cuica'),(nota_79,'Open Cuica'), (nota_80,'Mute Triangle'),(nota_81,'Open Triangle')) nota_pad_verde=models.CharField(max_length=2, choices=notas, default=notas[0][0]) nota_pad_gris=models.CharField(max_length=2, choices=notas, default=notas[0][0]) nota_pad_azul=models.CharField(max_length=2, choices=notas, default=notas[0][0]) nota_pad_amarillo=models.CharField(max_length=2, choices=notas, default=notas[0][0]) nota_pad_rojo=models.CharField(max_length=2, choices=notas, default=notas[0][0]) -
Django python d3 csv file
I have a problem with displaying charts in Django using D3 with csv file. Here is my code: Home.html : {% load static %} d3.csv("{% static 'webapp/data/rigresult.csv' %}", function(error, data) { data.forEach(function(d) { d.rig_name = +d.rig_name d.ind_pub = +d.ind_pub; }); Views.py : def test(request): t = get_template('webapp/home.html') html = t.render() return HttpResponse(html) urls.py : urlpatterns = [ url(r'^$', views.test, name='Home') ] Can someone help me this is for my final year project -
Django admin history
I'm working on a Django application which allows users to search in special forms. And I would like to keep in history what user searched. How I can do this? I was searching in doc, but i coludn't find this -
Django ModelMultipleChoice validation error
I'm trying to send a dynamic amount of selections of checkboxes on obj.html to the /items function. I'm getting the error "Select a valid choice. 1234 is not one of the available choices." But you'll notice that I print the queryset of choices from #views.py, it outputs that 1234 is contained in the flat queryset, with quotes around it. print(form.fields['choices'].queryset) # Console output ['1234', '1243',...] Why is 1234 not one of the available choices? I've tried putting quotes around the value attribute in the input form but it doesn't work. The items function stops because the data is not valid. How can I solve this? # forms.py class ItemForm(forms.Form): choices = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, queryset = Sampledata.objects.none()) # views.py def obj(request, object_id,): data = Sampledata.objects.filter(id=object_id) form = ItemForm() form.fields['choices'].queryset = list(data.values_list('value', flat=True)) print(form.fields['choices'].queryset) return render(request, 'obj.html', {'data':data,'form':form}) def items(request): if request.method == 'POST': form = ItemForm(request.POST) # check whether it's valid: if form.is_valid(): ... # obj.html <form action="/items" method="post"> # Many of these spread out throughout the page {% for obj in data %} <input type="checkbox" name="choices" value="{{obj.value}}"> {% endfor %} <input type="submit" value="Submit">