Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to replace re "." in Django template url tag
I have Django url routes that looks like this: app_name = 'courses' urlpatterns = [ url(r'./(?P<courseid>[0-9]+)/$', views.viewcourse, name='view_course'), url(r'./(?P<courseid>[0-9]+)/review/$', views.reviewcourse, name='review_course') ] The "." in the regular expression will usually be replaced by a slug, e.g.: courses/computer-science/3/ Now I need a link in my 'view course' template to take the user to the review page, i.e: courses/computer-science/3/review/ I could do this by simply appending review to the current url: {{ request.path }}review However, I would rather do it the 'correct' way using a template url tag {% url 'courses:review_course' courseid=course.pk %} However, this produces: courses/30/review, which of course fails. Is it possible to generate the correct link using the {% url %} tag without having to change the "." into a name capture parameter? -
Django deployment on Heroku, upgrading to Cedar-14, Import Settings Error
ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?) I built this app back in 2013-2014, and it hasn't seen much maintenance since then. But there's a problem now, some AWS keys need to be changed, but I can't deploy the app. git push heroku master results in a failed build unless I do heroku config:set DISABLE_COLLECTSTATIC=0 So, I did that, knowing it would probably break the site, but it never even gets to that point, because then I find out I can't deploy until I upgrade to Cedar-14. Ok, so I do that, then push, and then I get ImportError on every dyno. app/web.1: ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?): cannot import name _uuid_generate_random app/celerybeat.1: ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?): cannot import name _uuid_generate_random app/celeryd.1: ImportError: Could not import settings 'settings.prod' (Is it on sys.path? Is there an import error in the settings file?): cannot import name _uuid_generate_random So I read here that I need to update Kombu. Ok, so I do … -
FormFields for (Admin)Inlines || Can't import InlineModelAdmin
I want to catch up some extra information within my Django Admin through some extra Fields. I want to use inlines for that purpose. I have: class YourModelForm(forms.ModelForm): slot_count_request = forms.IntegerField(label='#-slot-size', initial=4 ) class Card_Group_proxy_inline(admin.TabularInline): model = SomeRandomModel form = YourModelForm This works fine for if I want to use a model within. I thought I can get rid of it, if I inherit from admin.InlineModelAdmin, but then I get an error: AttributeError: module 'django.contrib.admin' has no attribute 'InlineModelAdmin' -
Number of customers per week
In my django project, it is possible to show every customer in the application with CustomerProfile.objects.all() and find the creation date of a specific customer with In [12]: cust = CustomerProfile.objects.get(pk=100) In [13]: cust.user.date_joined Out[13]: datetime.datetime(2017, 7, 28, 14, 43, 51, 925548) In [14]: cust Out[14]: <CustomerProfile: Chantal Goyette's customer profile> According to the creation date, I would like to make a listing of how many customers has been created for each week. An example of the result could be ... week 28 : [ 09/07/2017 - 15/07/2017 ] - Count : 201 customers ... I probably need a range start_date and end_date where we will list that kind of information. start_date will be the date of the first customer created and the first week create would be the week of this first date. Obviously, the end_date is today and the last week est the week of this end_date. Sorry, I am a very new programmer in python/django. Could anyone have an idea how I could implement such information? -
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