Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.ValidationError: ["'69,999.78' value must be a decimal number."] how to solve?
i send data via js,and i split, so i already parse my price from string to decimal, but it still doesn't work help me pls this is error django.core.exceptions.ValidationError: ["'69,999.78' value must be a decimal number."] he said that my geting price is not a number and my price is a list wtf? i already check it via print(type()) it sais that it is a decimal views.py def basket_adding(request): return_dict = {} session_key = request.session.session_key data = request.POST product_id = data.get("product_id") product_name = data.get("product_name") product_price = Decimal(data.get("product_price")) product_size = data.get("product_size") product_related = data.get("product_related") product_all_price = data.get("product_all_price") sz = sizes_for_products.objects.get(size_name=product_size) product_himslef = Product.objects.get(id=product_id, size_of_product=sz, category_of_rel=product_related) new_product, created = ProducInBasket.objects.get_or_create(session_key=session_key, product=product_himslef, defaults={"session_key":session_key, "product_name":product_name,"product_price":product_price,"product_size":sz,"product_related":product_related,"product_all_price":product_all_price}) if not created: new_product.product_price = product_price new_product.product_size = sz new_product.product_related = product_related new_product.product_all_price = product_all_price return_dict["products"] = list() product_in_basket_filter = ProducInBasket.objects.filter(session_key=session_key, is_active=True) for item in product_in_basket_filter: product_dict = {} product_dict["product_id"] = item.product_id product_dict["product_name"] = item.product_name product_dict["product_price"] = item.product_price product_dict["product_all_price"] = item.product_all_price product_dict["product_size"] = item.product_size product_dict["product_related"] = item.product_related return_dict["products"].append(product_dict) return JsonResponse(return_dict) -
Re-install src/lib/python folder in a Django project
I have a Django project and I messed up with the src/lib/python folder (I know I shouldn't have but that's the case) and now I have missing files and folders. How can I re-install the python folder in order to retrieve the missing files? -
Django rest_framework: child object count in serializer
I need to count the number of children an object has and return this value in my API via the object serializer. I also need to count a subset of these children objects. I have a Task object with children Asignees. In my API when I query the tasks I want to have the following data set returned: [ { label: "Cross the bridge", count_assigned: 5, count_completed: 3 }, { label: "Build a fire", count_assigned: 5, count_completed: 2 } ] How would I do this? I have found the .annotate() method but that result is not available in the serializer class. models.py class Task(models.Model): label = models.CharField(max_length=255,null=False,blank=False) class Assignee(models.model): task = models.ForeignKey(Task, related_name='assignees', on_delete=models.CASCADE, blank=True, null=True) person = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) completed = models.DateTimeField(null=True,blank=True) serializers.py from rest_framework import serializers from .models import Task, Assignee from people.serializers import PersonSerializer class AssigneeSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() person = PersonSerializer(read_only=True) class Meta: model = Assignee fields = ('id','task','person','completed') read_only_fields = ['id'] class TaskSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Task fields = ('id', 'label') read_only_fields = ['id'] -
Fullpage.js not at the top of the screen
I am having a problem with fullscreen js. The problem is that the fullpage is not at the top of the screen: This is my HTML(Im using Django): {% extends 'layout/app.html' %} <body> {% block content %} <div id="fullpage"> <div class="section" id="section1">Some section</div> <div class="section">Some section</div> <div class="section">Some section</div> <div class="section">Some section</div> </div> {% endblock %} </body> The base.html where index.html extends from: {% load static %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="{% static 'Portfolio/css/normalize/normalize.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'Portfolio/css/fullpage/jquery.fullPage.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'Portfolio/css/bootstrap/bootstrap.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'Portfolio/css/style.css' %}" /> <title></title> </head> <body> {% block navbar %} {% endblock %} {% block content %} {% endblock %} <script src="{% static 'Portfolio/js/bootstrap/bootstrap.min.js' %}"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script> <script src="{% static 'Portfolio/js/fullpage/jquery.fullPage.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $('#fullpage').fullpage({ //sectionsColor: ['#1bbc9b', '#4BBFC3', '#7BAABE', 'whitesmoke', '#ccddff'], anchors: ['Welcome', 'Portfolio', 'Skills', 'About', 'Contact'], menu: '#menu', scrollingSpeed: 1000 }); }); </script> </body> </html> And this is the CSS: #section1 { background-image: url(../images/bg.png); background-size: cover; } I have tried setting margin : 0 i also have normalize.css linked. So there is no margin or padding applied to the fullpage … -
All suggestions are not coming after using Elasticsearch completion suggester
Suppose I have 27 rows for (select * from table where name like "s%") and while testing the API using elasticsearch with query as only "s" it is giving me only 11 names.Same behaviour is happening for other single character searches.All the rows have been indexed properly using the Context Suggester API.I'm using elasticsearch v-5.5.Following is my view in python Any help is appreciated.:slight_smile: class AutoCompleteUsersView(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) def list(self, request): query = request.GET.get('q') es = connections.create_connection(hosts=[elasticsearch_url], port=80, timeout=20) body = { "suggest": { "my-suggest" : { "prefix" : query, "completion" : { "field" : "suggest","fuzzy" : {"fuzziness" : 2},"size":20}}}} body_1 = {"suggest": {"my-suggest": {"prefix": query, "completion": {"field": "suggest", "size": 20}}}} if len(query)>3: res = es.search(index="autoidx", doc_type="user_search", body=body) elif len(query)== 1: res = es.search(index="autoidx", doc_type="user_search", body=body) else: res = es.search(index="autoidx", doc_type="user_search", body=body) a = res['suggest']['my-suggest'][0]['options'] b = [] for i in range(len(a)): b.append(a[i]['text']) b = set(b) c = list(b) ls = [] for i in range(len(c)): c[i] = c[i].lower() ls.append(list(OrderedDict.fromkeys(c))) print(c) return Response({"suggestions":ls}) -
File Uploads in Django from urllib
I have small django app where you can upload PDF files. In the past only human beings used the web application. In the future a script should be able to upload files. Up to now we use ModelBackend for authentication (settings.AUTHENTICATION_BACKENDS) Goal A script should be able to authenticate and upload files My current strategy I add a new user remote-system-foo and give him a password. Somehow log in to the django web application and then upload pdf files via a script. I would like to use the requests library for the http client script. Question How to login into the django web application? Is my current strategy the right one, or are there better strategies? -
AttributeError: 'Options' object has no attribute 'get_all_field_names'
I am trying to add MultilingualModel . I am using https://pypi.python.org/pypi/django-multilingual-model/0.6 but i keep getting the error: File ".../lib/python2.7/site-packages/multilingual_model/models.py", line 100, in __getattr__ translated_fields = self.translations.model._meta.get_all_field_names() AttributeError: 'Options' object has no attribute 'get_all_field_names' -
Django 1.11: Dynamic Javascript to load Google Map markers
Currently I have a maps.js static file, which I load using: <script type="text/javascript" src="{% static 'scripts/maps.js' %}"></script> However, since maps.js is static, I can't load tags such as {{ model.location }} , {{ model.lat }} , {{ model.lng }} etc. I tried adding maps.js to my users app folder, as so: users/templates/users/maps.js And inside that js I loaded template tags defined above. In my views.py I did: def index(request): js_file = "users/templates/users/maps.js" return render(request, "users/template.html", context={"js_file": js_file }) #template.html <script scr="{{js_file}}"></script> However, I get the error that the file could not be found -
Django: Querying the Database
Here's my model, class Question(models.Model): user = models.ForeignKey(User) followers = models.ManyToManyField(User, related_name='user_follow') I was wondering, how can I filter out the 3 most followed questions by the Users? Thank You :) -
Django: Tuple choices with integers not working in template
I have a few choices like so in my Django models: lead = 'Lead' contact = 'Contact' CHOICES = ( (lead, 0), (contact, 1) ) When using an if statement to display an object property in the template then it doesn't work (however doesn't display any errors): {% if object.choice == 0 %} {{ object.choice }} # This doesn't display anything {% endif %} However, the following does work: {% if object.choice == 'Lead' %} {{ object.choice }} # This works {% endif %} Even when I switch the choices (like (lead, 'Lead')) then only the == 'Lead' works and not the == 0 Why does this not work with integers and only with strings? Thanks -
Django admin and a lot of foreign keys
Django==1.11.5 Could you help me with admin site. I have a lot of models related to each other as one-to-many: Frame | \Item | \ | \ | \ | \ | \Sheet | | \ItemFile |\Image | |\File | \Note Well, a frame contains many items etc. Let's illustrate just by these three models and their admin classes: models class Frame(models.Model): pass class Item(models.Model): frame = models.ForeignKey('frames.Frame', blank=False, null=False, on_delete=models.PROTECT, verbose_name=_("frame")) class Sheet(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT, verbose_name=_("item")) admin class FrameAdmin(admin.ModelAdmin): inlines = [ItemInline] class ItemInline(admin.StackedInline): inlines = [SheetInline] class SheetInline(admin.StackedInline): inlines = [ImageAdmin] The problem is that I fail to organize a minimally decent admin. These inline classes are not suitable. In admin if I edit a frame, items are shown. But sheets don't. If I organize sheets through admin.ModelAdmin, then I will have to constantly switch context: create a Frame, at its edit page create items. Then go admin home, create a sheet etc. What I would like to do. From a frame instance create an item, from item create sheet. And the values for their foreign keys should be input automatically. Is it possible to organize that smoothly? -
Expose port 8000 using docker and django
I'm trying to do a copy of my django image that I found here: https://hub.docker.com/r/library/django Well, at this point the image is working good, but I'm trying to generate a container from this one. Well using the commands: $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3c3e94ff32e7 django:latest "python3" 18 hours ago Exited (137) 17 hours ago django $ docker images -a REPOSITORY TAG IMAGE ID CREATED SIZE django latest eb40dcf64078 9 months ago 436MB Using: $ docker commit django fmf $ docker run -p 8000:8000 -td fmf /bin/bash Now, I have the container fmf and I generated a new django project using: # django-admin startproject test # python manage.py runserver 8000 But, this port is not open (or at least I can't see any response there). I'm not sure if the port is not open and using a bridge, but I get no reponse from this container. What I'm doing wrong? -
Making multiple API calls in a Django web page
I am showing a list of objects in my page. Now I want to make API calls for each of these objects and show additional information based on the API get response. What is the best way to do this asynchronously. -
Using foreign key of the UserCreationForm model User
I have made a signup page using built in UserCreationForm of django. signup.html class UserCreationForm(UserCreationForm): email = EmailField(label=_("Email address"), required=True, help_text=_("Required.")) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user But I also need to make other tables in models.py. So if in another table category I need to make a foreign key of the primary key of this built in User of UserCreationForm. What is the primary key in this? models.py class category(models.Model): uid=models.ForeignKey(#) cname=models.CharField(max_length=20) def __unicode__(self): return u"{} {}".format(self.uid, self.cname) class Meta: db_table="category" What do I write in place of # ?? -
Django REST returns 404 when URL param is changed
I'm using Django REST framework to create an API that supports JSON and CSV output. I have this line in my urls.py: url(r'^api/events/$', views.EventsView.as_view(), name='events'), EventsView looks like this: class EventsView(APIView): def dispatch(self, request, *args, **kwargs): return super(EventsView, self).dispatch(request, *args, **kwargs) def get(self, request): logger.info("Here") events = EventsQuery(request) if events.is_valid(): events.build_response() return events.get_response() If I visit /api/events/?format=json I get a set of results as valid JSON, and I see "Here" logged to my log file. If I visit /api/events/?format=csv I get a 404 response with a JSON body of { "detail": "Not found." } ...and nothing is logged. The lack of logging is what's throwing me. It's like it's not even getting to the EventsView class, but how could changing a querystring value in the URL stop it being routed to that class? And how do I find out where it IS being routed to? -
django makemigrations ValueError
I am learning django. When I type python manage.py makemigrations, it shows error in the picture. The error message is strange for me. Because like 'blog.userinfo' is my previous project's models content. when i create a new project and try makemigrations the error will appear. models.py is empty in the new project Why I have this error? how can I solve this problem. -
getting required data from database to the table contents in a django template?
def cluster_detail(request, state_id, region_id, cluster_id): if not request.user.is_authenticated(): return render(request, 'music/login.html') else: user = request.user state = get_object_or_404(State, pk=state_id) region = get_object_or_404(Region, pk=region_id) cluster = get_object_or_404(Cluster, pk=cluster_id) mnsstrength = 0 mlastrength = 0 mnstotal = 0 mlatotal = 0 for school in cluster.school_set.all(): mnsstrength = mnsstrength + school.mns_strength for school in cluster.school_set.all(): mnsset = Mnsavergae.objects.filter(school=school) mns = mnsset.latest('mnsaverage_date') mnsavg = mns.mnsaverage mnstotal = mnstotal + mnsavg * school.mns_strength clumnsavg = mnstotal/mnsstrength for school in cluster.school_set.all(): mlastrength = mlastrength + school.mla_strength for school in cluster.school_set.all(): mlaset = Mlaavergae.objects.filter(school=school) mla = mlaset.latest('mlaaverage_date') mlaavg = mla.mlaaverage mlatotal = mlatotal + mlaavg * school.mla_strength clumlaavg = mlatotal/mlastrength return render(request, 'music/cluster_detail.html', {'state': state, 'mnsstrength': mnsstrength, 'mlastrength': mlastrength, 'mnstotal': mnstotal, 'mlatotal': mlatotal, 'clumnsavg': clumnsavg, 'clumlaavg': clumlaavg, 'region': region, 'cluster': cluster, 'user': user}) In the cluster_details page I want to show a table of all the schools in the particular cluster(which can be a town or city). In the columns of the table I wanted to show school name, strength of mns course, strength of mla course which are actual attributes to School class. So I could simply use a for loop to get the table contents. But then I am stuck with this problem where I … -
Django queryset get max id's for a filter
I want to get a list of max ids for a filter I have in Django class Foo(models.Model): name = models.CharField() poo = models.CharField() Foo.objects.filter(name=['foo','koo','too']).latest_by_id() End result a queryset having only the latest objects by id for each name. How can I do that in Django? Edit: I want multiple objects in the end result. Not just one object. -
Django How to specify the upload to location for FileField from views.py
Say you have a modelform with a FileField: class Book(models.Model): book_title = models.CharField(max_length = 100, blank = False, null = False) book_teaser = models.FileField(blank = True, null = True) author = models.ForeignKey(related_name = 'books', blank = True, null = True) ... class Author(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, null = True, blank = True) ... The Book model does not have a direct relationship with User model. If you want to upload the PDF files under: user/books/ # app_name is books How do you go about specifying the upload_to location in views.py. The docs show how to specify the upload location in the models.py using either a static address, which does not work for me, or a callable: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) But, unlike the docs' example, the model does not have direct foreign key in order to use instance.user.id So, how would you specify the upload location from views.py depending on what user is looking at the site? -
Django uploading images
I want to upload images in the django admin interface. During development everything works fine but when I put the files on my server it doesn't work. I have two different paths on my Server. One where I put all my source files and one where I put all the static files. Path for source files:/htdocs/files/project/ Path for static files: /htdocs/html/project/ If I upload an image, then it is saved in /htdocs/files/project/media/. But I want to save it in /htdocs/html/project/. How can I change the path? Here are my settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), '/var/www/ssd1257/htdocs/html/' ) And here is my model: class News(models.Model): title = models.CharField(max_length=200, null=False) date = models.DateField(null=False, default=datetime.now) text = models.TextField(null=False, blank=True) image = models.ImageField(upload_to="./news/") -
Django UserCreationForm extension
can i add fields like address,city,state,country,pincode and security question and answer to the extension of UserCreationForm that currently contains username,email,password1 and password2. if yes then please illustrate how? forms.py class UserCreationForm(UserCreationForm): email = EmailField(label=_("Email address"), required=True, help_text=_("Required.")) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user -
Django REST and ModelViewSet filtering
I was previously using APIViews such as the following: views.py class AllProgramsApi(APIView): def get(self, request): user = self.request.user userprograms = Program.objects.filter(user=user) serializer = ProgramSerializer(userprograms, many=True) return Response(serializer.data) here's my model: class Program(models.Model): program_name = models.CharField(max_length=50) program_description = models.CharField(max_length=250) cycles = models.ManyToManyField(Cycle) is_favourite = models.BooleanField(default="False") user = models.ForeignKey(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('programs:program', kwargs={'pk': self.pk}) def __str__(self): return self.program_name Now I've discovered ModelViewSet, which looks very convenient, but I can't seem to be able to filter for the user as I was previously doing in the APIView. my attempt at views.py with ModelViewSet is the following and it works but I get all the content and not just the content related to a single user. class AllProgramsApi(ModelViewSet): serializer_class = ProgramSerializer queryset = Program.objects.all() How can I tweak the ModelViewSet so that it displays only the content related to the user who sends the request? What is the best method? Thanks. -
Django: Prevent Looping in between the Loop
I have a for loop in django! {% for abc in xyz %} {% endfor %} The variable 'xyz' contains data from 2 separate models! So, Is there a way for printing entire data by looping just once in a way like, Data from first Model DATA DATA etc. Data from second Model Data Data etc. If I'm doing this in just one loop then "Data from first/second Model" is also printed equal number of times as actual data. I wants to print it one without using multiple loops. So, is there any way to break this loop in between the loop itself & add some constant data? -
How to validate / change modelformset information when 2 forms are dependent on each other?
I have a django application which saves some user data using a regular form and a modelformset when the user clicks 'save'. So on a given page the user sees - there is the regular modelform (Benefit) and then below that on the same page is the modelformset with one 'save' button. When the user saves, both the modelform and the formset save their respective information. I have found that when working with modelformsets you should use the clean method for validation. Here is mine: class BaseDependentFormSet(BaseModelFormSet): def clean(self): b = Benefit.objects.get(id=self.data['benefit']) if 'PPO' in b.name: for d in self.cleaned_data: #print(d['has_medical']) #print(d['med_group_id']) d['med_group_id'] = '' print(d['med_group_id']) return self.cleaned_data As you can see - if the user has selected 'PPO' in the Benefit modelform, we eliminate any med_group_id they have associated in the modelformset. This code above does in fact erase the med_group_id as expected, but then when the page reloads, the med_group_id is still listed. My save looks like this: if dep_formset.is_valid(): for form in dep_formset: if form.is_valid(): try: form.save() Which saves fine - except that it's not saving the 'cleaned' values (empty) for med_group_id, it retains the original values. I had read somewhere that altering the data in the … -
Django complex query based on dicts
Tldr of Problem Frontend is a form that requires a complex lookup with ranges and stuff across several models, given in a dict. Best way to do it? Explanation From the view, I receive a dict of the following form (After being processed by something else): {'h_index': {"min": 10,"max":20}, 'rank': "supreme_overlord", 'total_citations': {"min": 10,"max":400}, 'year_began': {"min": 2000} 'year_end': {"max": 3000} The keys are column names from different models (Right now, 2 separate models, Researcher and ResearchMetrics), and the values are the range / exact value that I want to query. Example (Above) Belonging to model Researcher : rank year_began year_end Belonging to model ResearchMetrics total_citations h_index Ideally: I want to show the researchers who fulfill all the criteria above in a list of list format. Researcher ID, name, rank, year_began, year_end, total_citations, h_index [[123, Thomas, professor, 2000, 2012, 15, 20], [ 343 ... ]] What's the best way to go about solving this problem? (Including changes to form, etc?) I'm not very familiar with the whole form query model thing. Thank you for your help!