Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM orderby exact match to be on top
I need to order the results based on the length of match in Django ORM. I have a Location table with countries in name field. I have a requirement to search the table with given text and order by exact match / most prominent match to be the top For example:- 1) if search string is 'America' then the result should be [America, South America, North America ..] in this case we found a complete match, which has to be the first element. 2) if search is port then the result should be ['Port Melbourne' 'Portsea', East Airport] in this case we found port to be a complete match before the delimiter. Any clue ? Thanks in advance -
Does Django AllAuth send a signal for signup email verified?
Allauth Signals I'm still uncertain after reading the docs concerning signals that the following signal is sent after the user verifies his signup email. allauth.account.signals.email_confirmed(request, email_address) Will that signal be fired when a user creates an account and clicks the verification link in the email or does it only get sent when the user updates an existing email? -
Can I limit the visible Collections in the Wagtail Admin Image Chooser?
I have a few Groups and Collections setup to take advantage of the Collections feature in wagtail. I have limited collection A to Administrators only. After logging in as a non-Administrator and clicking on the 'CHOOSE AN IMAGE' button to bring up the image chooser, there's a drop down for 'Collection' and it includes all of my collections, including the restricted collection A. Is it possible to only show collections and images that the user owns similar to how the 'Images' menu item works? Wagtail: 1.12.2 Django: 1.8.18 -
Having trouble with Django forms. Not understanding this error
I'm trying to set up a form on Django that displays inputs on the page, but I get this error. django.db.utils.OperationalError: no such table: firstapp_post This doesn't happen right away, but when I try to use the submit feature on my form. Right now this is what I have as my models: from django.db import models from django.contrib.auth.models import User class Post(models.Model): post = models.CharField(max_length=500) user = models.ForeignKey(User) These are currently my forms: from django import forms from firstapp.models import Post class IndexForm(forms.ModelForm): post = forms.CharField() class Meta: model = Post fields = ('post',) This is my views file: from django.shortcuts import render, redirect from firstapp.forms import IndexForm from django.views.generic import TemplateView class HomePage(TemplateView): template_name = 'home/home.html' def get(self, request): form = IndexForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = IndexForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() text = form.cleaned_data['post'] form = IndexForm() return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) This is my base.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Assignment 4</title> <link rel='stylesheet' href='{% static "css/base.css" %}'/> </head> <body> <p>{{ variable }}</p> {% block body %}{% endblock %} <script src= '{% static "js/base.js" %}'></script> … -
Django: Auto suggest in text field
I'm trying to work out how to have suggestions in a text field using Django (1.11). I've been going through the documentation of autocomplete-light but so far I've not been able to figure out my use case. The documentation on that package is not easy to understand for a total noob :) I want a text field that gives suggestions as you type, were the suggestions come from the database. E.g. if it's a list of food items the user types in 'C' and it suggest Chicken and Crisps as they have been entered by someone earlier. I also want the user to be able to enter Cheese even though it hasn't been entered before. The suggestion "algorithm" just has to check if what has been entered matches the first characters of already existing items. Here is a boiled down version of the django project: urls.py from django.conf.urls import url from django.contrib import admin from testapp.views import TestView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'$',TestView.as_view()) ] models.py from django.db import models class TestModel(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name forms.py from django import forms from .models import TestModel class TestFormClass(forms.ModelForm): class Meta: model = TestModel fields = ('__all__') views.py from … -
Why the form is not JSON serializable?
I am using Django and I am trying when a button is clicked to get data from the database and fill a form with them through AJAX. I get the error TypeError: Object of type 'EditProductForm' is not JSON serializablefrom the edit_product_view in my views.py Below is the code I am working with: -urls.py from django.conf.urls import url from . import views app_name = "products" urlpatterns = [url(r'^products', views.ProductsView.as_view(), name="products"), url(r"^product/new", views.add_new_product_view, name="add_new_product"), url(r"^product/(?P<id>[0-9]+)/edit/", views.edit_product_view, name="edit_product")] -views.py from django.views.generic import DetailView, ListView, TemplateView from django.http import JsonResponse from django.shortcuts import render, get_object_or_404 from . import models from products.forms import AddNewProductForm, EditProductForm def index(request): return render(request, 'products/products.html') class ProductsView(ListView): context_object_name = "products" model = models.Product template_name = "products/products.html" form = AddNewProductForm() def get_context_data(self, **kwargs): context = super(ProductsView, self).get_context_data(**kwargs) context["products"] = models.Product.objects.all().order_by("title") context["form"] = self.form return context def add_new_product_view(request): if request.method == "POST": form = AddNewProductForm(request.POST) if form.is_valid(): form.save(commit=True) return JsonResponse({'msg': 'Data saved'}) else: print("ERROR FORM INVALID") return JsonResponse({'msg': 'ERROR FORM INVALID'}) else: form = AddNewProductForm() return JsonResponse({'form': form}) def edit_product_view(request, id): print(request.method) instance = get_object_or_404(models.Product, id=id) form = EditProductForm(instance=instance) if request.method == "POST": form = EditProductForm(request.POST, instance=instance) if form.is_valid(): form.save(commit=True) return JsonResponse({'form': form}) else: print("ERROR FORM INVALID") return JsonResponse({'form': form}) -products.html … -
Error migrating MySQL database into Django. Unexpected host name
I am trying to migrate a MySQL db into Django. I created a simple database when I followed a tutorial, but now I am trying to migrate my actual db into the project. I modified settings.py to look like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pulse', 'USER':'root', 'PASSWORD':'zzz', 'HOST':'yyyy-backend.cluster-xxx.us-east-1.rds.amazonaws.com', 'PORT':'3306', } My error: mysql_exceptions.OperationalError: (2005, "Unknown MySQL server host 'mysql://dev-backend.cluster-xxx.us-east-1.rds.amazonaws.com:3306' (74)") Where the heck is it getting dev-backend.cluster as the database from? My migrate command: python manage.py makemigrations python manage.py migrate -
Django validation with ReactJS and Redux Form
Currently, I am working on a project that uses ReactJS, Redux, and Django. I have a ReduxForm for registration. <h3>Company's basic information</h3> <Field // Redux form props name="name" component={renderTextField} label="Company's Name" // Custom props required={true} type="text" placeholder="Company's Name..." onBlur={this.handleFieldsChange.bind(this)} /> So a single field looks something like that. When the form is submitted the information is sent over to Django to store. I am unsure of how validation works between these two. What I am wanting to do is check if a company exists with that name. Organization.objects.filter(company_name=name) So I do this to and I am able to see if it exists. If it does, then I want to make it known to the user that they cannot have the same name. This is where I am unsure of how to make this work. I did something like raise ValidationError({'name': ["A company named '%s' already exists" % name,]}) However, this only make the form not submit. The validation error only appears in the log. Perhaps someone can point me in the right direction. -
Use IP to get Province/City and use it in generic Listview
I'm working on my first Python and Django project. I want to get a the user's province/city and pass it as context that I can use in my template. Right now I am hard coding this. For example. _province = "California" The stack I'm on is: Python 3.6 Django 1.11 Heroku Hobby I've read through a number of posts but there appears to be a lot of moving parts and I don't know what I don't know. In my ListView I've had to hardcode in the province information. I want to replace this line with a function that will return the user's province or city based on the user's IP address. I want this to work in development and in my production. I want to be able to call the province/city in my template. The snippet from get ip of user looks good. What do I need to install and import? Where do I place the get_client_ip function. Inside the ListView Class? Why does this function not have a (self)? Is this python 2.x? Where does request get passed from? What does request.META.get do? Do I need to set META in my base.html template? How do I get the META … -
How can I remove the add and edit buttons from a TabularInline admin field?
I have models A, B, and AB. A objects have a ManyToMany field A.m that can link to many B objects, through my intermediary model AB. I have a very nice TabularInline section full of AB objects, on my admin page for my A model. All is well. Except that the TabularInline section shows Add and Edit links for the B object in each AB object's row, and I want to remove those buttons. I still want to be able to add, edit and remove AB objects rows, just not the B objects they reference. I have tried setting the can_add_related, can_change_related, can_delete_related properties to False, but this does nothing. class ABInline(admin.TabularInline): model = AB def get_form(self, request, obj=None, **kwargs): form = super(ABInline, self).get_form(request, obj, **kwargs) form.base_fields['b'].widget.can_add_related = False form.base_fields['b'].widget.can_change_related = False form.base_fields['b'].widget.can_delete_related = False return form Is this a bug? Or is there a different way to accomplish this for TabularInline fields? -
How do I correct this *non-nullable field* error in my Django Project?
I want to migrate the following model and create a new database. from django.db import models from django.contrib.auth.models import User from Self import settings class Identity_unique(models.Model): NIS_Identity = models.CharField(max_length=500, default=0) user = models.ForeignKey(settings.AUTH_USER_MODEL) date = models.DateTimeField(auto_now=True) However when I run the makemigrations command, it gives me this error : You are trying to add a non-nullable field 'id' to identity_unique without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I have added the default argument in the NIS_Identity field but I am still getting that error. Here is my modelForm form : from django import forms from home.models import Identity_unique class Identity_form(forms.ModelForm): NIS_Identity = forms.CharField() class Meta: model = Identity_unique fields = ('NIS_Identity',) -
Django, how the conditional queries works?
I have a question, I think is very basic but I didn't find answer for this. Based in the thread django conditionally filtering objects Using the same example: user = User.objects.get(pk=1) category = Category.objects.get(pk=1) qs = Item.objects.filter(user=user, date=now()) if category: qs = qs.filter(category=category) When the qs variable retrieve the results? Because, if the line Item.objects.filter(user=user, date=now()) gives as result 1 million of records (after filter the category), those records will be loaded in memory? Or the queries are retrieving the information at the same time of the render view (or whatever method I would use) ? -
TypeError: unhashable type: 'list' when trying to download image by link. Python + Django
Trying to save file by link, but face TypeError: unhashable type: 'list' import requests import lxml page = requests.get('https://karabas.com') for link in links: event_page = requests.get(link) tree_event_page = html.fromstring(event_page.content) image = tree_event_page.xpath('//figure[@class="photo"]/meta/@content') f = open('00000001.jpg','w+') f.write(requests.get(image).content) image variable is a link. What's wrong with the way I am trying to download image? -
Map Django QuerySet items
Is there a way to map Django QuerySet items not triggering its evaluation (returning a QuerySet)? -
Facebook API Login clears out Django session
I have a Django application that uses an AngularJS front end. Users can either login with an email/password, or by using their Facebook account. There is a bit of data that I need to hold onto for a user before, and after they log in. Since logging in with email/password is asynchronous with Angular, I don't have to worry about saving anything to my Django session, just to an AngularJS root scope variable. Using Facebook reloads the page though, clearing out all the root scope variables, so I have to save that little piece of info to a session variable, and retrieve it after the user logs in with Facebook, and the page reloads. I set some breakpoints, and debugged the application in my Django view functions that save the session variable. I can see that the session has the right information {'veh_info_id': 37} After the Facebook login however I check the session at a breakpoint in another view function, and it just has a bunch of Facebook session variables { 'auth_user_backend': value, 'auth_user_hash': value, 'auth_user_id': value, 'facebook_state': value, 'social_auth_last_login_backend': value } The weird part is if I leave the breakpoints in, and slowly go through it, the session has … -
Django - add choice field to django admin list_filter
This is one of my django admin classes: class InactiveSiteAdmin(SiteAdmin): change_list_template = 'admin/change_list_inactive.html' list_display = ('is_active', 'thumb', 'name', 'show_url', 'get_desc', 'keywords','category', 'subcategory', 'category1', 'subcategory1', 'group') fields = ('name', 'url', 'id', 'category', 'subcategory', 'category1', 'subcategory1', 'description', 'keywords', 'date', 'group', 'user', 'is_active', 'date_end',) readonly_fields = ('date', 'date_end', 'id') list_display_links = ('name',) actions = [activate_sites, activate_sites1, ] def get_queryset(self, request): return Site.objects.filter(is_active=False) def response_change(self, request, obj): return redirect('/admin/mainapp/site/{}/change/'.format(obj.id)) def has_add_permission(self, request): return False "activate_sites" action is for accepting selected object (make it visible) and for send confirmation email to obj.email (email field of selected object). I would like to add another field to list_display - for example "email_text" where superuser would choose correct text message (using choice field). Is it possible? I have 3 objects for example. I would like to give opportunity to activate all 3 objects and select different text messages to each object. -
Django:Fetching values of single column
I have class holiday(models.Model): h_date=models.DateField() h_description=models.CharField(max_length=200) when I query h_list=holiday.objects.all().values('h_date') I get output as <QuerySet[{'h_date':datetime.date(2017,5,1)},{'h_date':datetime.date(2017,4,2)}]> But I need output as 2017-05-01 2017-04-02 How can I get that output with just querying the database? -
Django ORM - Get period between truncated objects in aggregation
everyone. I have the next model in my models.py: ` class Order(models.Model): ... created_at = models.DateTimeField(null=True) ` In my viewv.py I have the next code for truncating orders by date: ` average_period_between_transactions = ( Order.objects .filter(shop_id=shop_id, shop_status_state='completed') .filter(Q(shop_status_state='completed') | Q(shop_status_state='refunded')) .exclude(transaction_id__isnull=True) .exclude(transaction_id__exact='') .annotate(trunc_value_date=trunc_value) .values('trunc_value_date') .annotate(c=Count('id')) .values('trunc_value_date', 'c') .filter(trunc_value_date__range=(start_date, end_date)) .order_by() ) ` It works well for truncate orders by date and getting a count of them. As I have date_created_shop with hours and minutes, I need to annotate an Average period between orders in my truncated orders instead of .annotate(c=Count('id')). And now I have not idea how can I do it by the help of django-ORM or some other libraries. Does someone have some ideas, or thoughts which can be helpful for my task? -
Vectorized with numpy
start_date = CustomerProfile.objects.filter(user__date_joined__gte=datetime.datetime(2017, 6, 1)).first().user.date_joined end_date = CustomerProfile.objects.last().user.date_joined while start_date < end_date: count = CustomerProfile.objects.filter(user__date_joined__date=start_date).count() test = 'There are {} customers during the day : {}'.format(count, start_date print(test) start_date += datetime.timedelta(1) In fact, instead of printing test, I would like to create vector with numpy. I don't want to store them in a list. How could I do such thing? Be aware that I want to create a numpy array with count, not test. What I want to obtain is (1) ... week 28 : [ 09/07/2017 - 15/07/2017 ] - Count : 201 customers ... What do I need to do with a numpy array? Compute several statistical indicators (mean, standard deviation, max, min, ...) Print them out in a django form which will look like (1) I will work with over than 50G. My system is able to tolerate it, but I want something which will not take to much place on my SSD card. -
Python decorator to disable a certain function crashing.
I have a function in python that's used in many views. Specifically its in a django app running under uwsgi. The function just fires tracking data into our database. I wanted to create a decorator that would disable that function for a specific call to the view that contains the function. Essentially: @disable tracking def view(request): track(request) //disabled by decorator The decorator works by replacing the global definition of track with a void function that does nothing. Since we're running this under uwsgi which is multithreaded if I replace a global definition it will replace the function for all threads running under the process, so I defined the decorator to only activate if the tid and pid are equivalent. Here: def disable_tracking(func): #decorator def inner(*args, **kwargs): original_tracker = pascalservice.track.track anon = lambda *args, **kwargs: None tid = lambda : str(current_thread().ident) pid = lambda : str(getpid()) uid = lambda : tid() + pid() current_uid = uid() cache.set(current_uid, True) switcher = lambda *args, **kwargs: anon(*args, **kwargs) if cache.get(uid()) else original_tracker(*args, **kwargs) pascalservice.track.track = switcher result = func(*args, **kwargs) cache.delete(current_uid) pascalservice.track.track = original_tracker return result return inner The wierd thing about this decorated function is that I'm getting occasional crashes and I want … -
Error: Could not resolve URL for hyperlinked relationship using view name "api:products-list"
I use django-rest-framework. I wanna add url field to each product item using HyperlinkedIdentityField in ProductSerializer but it says there is something wrong. I get an error: Could not resolve URL for hyperlinked relationship using view name "api:products-list". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.I don't even know why it can happen, because I specify correct view_name and it should work fine. Thanks for help! urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('catalog.urls', namespace='blog')), url(r'^api/', include('catalog.api.urls', namespace='api')), ] catalog/api/urls.py urlpatterns = [ url(r'^categories/$', CategoryListAPIView.as_view(), name='categories-list'), url(r'^products/$', ProductListAPIView.as_view(), name='products-list'), url(r'^products/(?P<pk>\d+)/$', ProductDetailAPIView.as_view(), name='product-detail'), url(r'^products/(?P<pk>\d+)/edit/$', ProductUpdateAPIView.as_view(), name='product-update'), url(r'^products/(?P<pk>\d+)/delete/$', ProductDeleteAPIView.as_view(), name='product-delete'), url(r'^categories/(?P<pk>\d+)/$', CategoryDetailAPIView.as_view(), name='category-detail'), url(r'^categories/(?P<pk>\d+)/edit/$', CategoryUpdateAPIView.as_view(), name='category-update'), url(r'^categories/(?P<pk>\d+)/delete/$', CategoryDeleteAPIView.as_view(), name='category-delete') ] catalog/api/serializers.py class ProductSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='api:products-list', lookup_field='pk', ) category = serializers.SerializerMethodField() def get_category(self, obj): return str(obj.title) class Meta: model = Product fields = ( 'url', 'id', 'title', 'details', 'slug', 'category', ) class CategorySerializer(serializers.ModelSerializer): products_count = serializers.IntegerField() class Meta: model = Category fields = ( 'id', 'title', 'slug', 'products_count', ) class CategoryUpdateSerializer(serializers.ModelSerializer): class Meta: model = Category fields = ( 'title', ) class ProductUpdateSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( 'title', 'details', 'category', ) catalog/api/views.py class CategoryListAPIView(ListAPIView): … -
django apache wsgi issue
i want open django server using apache and mod_wsgi. i wrote down as below sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi and create django project and app and i add my bot in setting.py and create virtual environment and using and add below code in seoultech/wsgi.py /django = mydirctory/ seoultech=project/bot =app / import os, sys sys.path.append('/home/django') sys.path.append('/home/django/venv/lib/python2.7/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "seoultech.settings") application = get_wsgi_application() and cd /etc/apache2/site-available/000-default.conf add code WSGIDaemonProcess seoultech python-path=/home/django/seoultech=home/django /venv/lib/python2.7/site-packages <VirtualHost *:80> ServerAdmin webmaster@localhost WSGIScriptAlias / /home/django/seoultech/wsgi.py <Directory /home/django/seoultech> <Files wsgi.py> Require all granted </Files> </Directory </VirtualHost> but sudo apachectl-k start i got error 'AH00526: Syntax error on line 1 of /etc/apache2/sites-enabled /000default.conf:Invalid command 'WSGIDaemonProcess', perhaps misspelled or defined by a module not included in the server configuration Action '-k start' failed.The Apache error log may have more information.' im looking forward to help -
Add view in the buttom of Django modeladmin
I have a blog made with Django where I write posts in markdown. I would like to add a view in the buttom of the admin page for each instance of the class Entry (my blog post class) such that I can get a preview of what the markdown looks like, while I'm writing. Just as you get a preview here on stackoverflow when you create a new post. I already have an admin class extending ModelAdmin: class EntryAdmin(admin.ModelAdmin): list_display = ('title','created') prepopulated_fields = {'slug': ('title',)} Is it possible to modify ModelAdmin further, such that it loads a certain html file (blogpost.html) and shows it in the buttom of the admin page? I made a lame picture to show exactly what i mean: NB: I know there are various tools such as Django admin plus, that allows one to add views to the admin interface, but not for each instance of an object. -
How to use temporary storage for objects in Django?
I have a crawler in Django project which crawls thousands of urls. Crawling is performed every two hours. There are multiple requests per second which can slower the database. This is a parse method from spider: def parse(self, response): httpstatus = response.status url_obj = response.request.meta['url_obj'] xpath = url_obj.xpath elements = response.selector.xpath(xpath + '/text()').extract() ... EXCEPTIONS ... Scan.objects.create(url=url, httpstatus=httpstatus, price=price, valid=True) As you can see, I have to access database after every request (tens in second) but this database is used by users too. Moreover, I can't use these Scan objects in frontend before the whole scanning is done. My idea is to create some kind of intermediary/temporary storage for newly created Scan objects and then, after scanning is done, move them to the main database. How can I do that? Do you have any ideas? -
STATIC_ROOT setting in Django
I am learning Django and have built a sample Django app. It works fine on my computer, but I am having trouble deploying it to Heroku. My root directory has the following structure: My setttings.py file has the following settings for static files: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' When I try to deploy to Heroku, I get the following error message: ImproperlyConfigured:You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path