Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
data must be QuerySet-like (have count() and order_by()) or support list(data) -- NoneType has neither
I am using Django-table2 for SingleTableMixin and I am getting this error which I am not able to come around. Error says I need to present data in query to be able to make it work. Following is the code and guidance is requested. class ProductListView(SingleTableMixin, generic.TemplateView): template_name = 'dashboard/catalogue/product_list.html' form_class = ProductSearchForm productclass_form_class = ProductClassSelectForm table_class = ProductTable context_table_name = 'products' def get_context_data(self,**kwargs): ctx = super(ProductListView, self).get_context_data(**kwargs) ctx['form'] = self.form ctx['productclass_form'] = self.productclass_form_class() return ctx def get_description(self, form): if form.is_valid() and any(form.cleaned_data.values()): return _('Product search results') return _('Products') def get_table(self, **kwargs): if 'recently_edited' in self.request.GET: kwargs.update(dict(orderable=False)) table = super(ProductListView, self).get_table(**kwargs) table.caption = self.get_description(self.form) return table def get_table_pagination(self): return dict(per_page=20) def filter_queryset(self, queryset): return filter_products(queryset, self.request.user) def get_queryset(self): queryset = Product.browsable.base_queryset() queryset = self.filter_queryset(queryset) queryset = self.apply_search(queryset) return queryset Traceback: Request Method: GET Request URL: http://localhost:8000/dashboard/catalogue/ Django Version: 1.8.16 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.flatpages', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'haystack', 'default.templatetags', 'treebeard', 'sorl.thumbnail', 'django_tables2', 'compressor', 'widget_tweaks', 'catalogue', 'catalogue.reviews', 'customer', 'customer.alerts', 'customer.notifications', 'customer.wishlists', 'analytics', 'partner', 'offer', 'order', 'address', 'basket', 'voucher', 'wishlist', 'shipping', 'promotions', 'payment', 'dashboard', 'dashboard.catalogue', 'dashboard.communications', 'dashboard.orders', 'dashboard.offers', 'dashboard.pages', 'dashboard.partners', 'dashboard.promotions', 'dashboard.ranges', 'dashboard.reports', 'dashboard.reviews', 'dashboard.shipping', 'dashboard.users', 'dashboard.vouchers', 'purl') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', … -
Django - Cannot assign, must be a instance
This issue was raised several times, though I guess I'm getting it from a different reason, or at least I can't tell how it's related. Django: 1.10.5, Python: 3.5.2 So, I have such models (simplified): class Parent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_created = models.DateTimeField(auto_now=True) class Child(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_created = models.DateTimeField(auto_now=True) parent = models.ForeignKey(Parent) def __init__(self, parent, *args, **kwargs): super(Child, self).__init__(*args, **kwargs) self.parent = parent Then, I'm trying to test some custom queryset method for child (method itself is not relevant): class ChildQuerysetDatabaseIntegrationTest(TestCase): default_parent = Parent() def setUp(self): super(ChildQuerysetDatabaseIntegrationTest, self).setUp() self.default_parent.save() def test_find_recent(self): # given for _ in range(1, 10): child = Child(self.default_parent) child.save() # when recent = Child.objects.find_recent() ordered = Child.objects.order_by('-date_created') # then self.assertEqual(list(ordered), list(recent)) This produces following error on the last line of test (fetching all entities): ValueError: Cannot assign "UUID('...')": "Child.parent" must be a "Parent" instance. Usually, when there's some mapping error, the error is thrown during entity saving, but here everything seems to persist successfully, but then fails on retrieval. The UUID object that is tried to be assigned to parent instance, is actually child's id object, which makes me even more confused. I tried changing object creation to Parent.objects.create(), but the … -
speech recognition while on the web and django as backend: Tornado, channels or something else?
my situation: I have a web page on which I want to be able to say something, a function for speech recognition gets initiated, triggers another function based on result and it updates the aforementioned web page without refreshing. I have all the "server" work done (and working) in python, my current server side solution is django which served me well till now but, in order to perform this task, it needs upgrading: of what sort, is what i'd like to know. I have looked at websockets,Tornado and the django channels project (simple ajax calls seem to be not enough) but I am unsure on the best structure for the job at hand. -
Optimizing pagination in function-based views (in Django)
In a class-based Django listview, when one allots a value to paginate_by, it ensures that the object_list available in get_context_data method is limited to only those objects that are needed for that particular page. E.g. get_queryset might return 1000 objects, but if a single page is to show 20 objects, then only 20 objects are available as object_list in get_context_data. This is a good optimization when dealing with large querysets. How can one create this same behavior in function-based views? Under typical implementation (and taking the aforementioned example), all 1000 objects would be evaluated and then used in pagination. That means that in this particular case, CBVs are definitively better than function-based views. Can function-based views provide the same functionality? An illustrative example would be great (or a 'no they can't' kind of answer works too). A function-based view with pagination: def paginated_objects(request,*args,**kwargs): obj_list = retrieve_object_list() #retrieves all 1000 objects paginator = Paginator(obj_list, 20) #20 objects served per page page = request.GET.get('page', '1') try: page = paginator.page(page) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) A paginated CBV: class PaginatedObjectsView(ListView): model = Objs paginate_by=20 def get_queryset(self): return retrieve_object_list() def get_context_data(self, **kwargs): context = super(PaginatedObjectsView, self).get_context_data(**kwargs) #the scope here … -
Partition/allocate ranges of primary key integers
Given RangeA of auto-incrementing primary key integers (1 to 32767) and RangeB (32768 to 2147483647). If a condition is true, save an object with a primary key assigned in the first block, else save it in the second block. How can this be done using Django and Postgres? Context: This is primarily to avoid creating multiple tables with identical columns. -
Issue with filter on Django
Please help to understand. I have a django application with REST API. Everything working, but i wanna to add filter by name and here i received the issue. There is a error message invalid literal for int() with base 10: 'B123456' And sure this is my code api.py class DatabaseByClientList(RetrieveUpdateDestroyAPIView): serializer_class = DatabaseSerializer def get_queryset(self): client_id = self.kwargs['client_id'] return Database.objects.filter(client_id=client_id) models.py class Database(models.Model): def __unicode__(self): return unicode(self.id) class Meta: ordering = ['db_name'] client_id = models.ForeignKey(ClientInfo) db_name = models.CharField(max_length=30, blank=True) db_host = models.CharField(max_length=30, blank=True) db_user = models.CharField(max_length=30, blank=True) db_pass = models.CharField(max_length=30, blank=True) db_type = models.CharField(max_length=30, blank=True) serializer.py class DatabaseSerializer(serializers.ModelSerializer): client_id = serializers.SlugRelatedField(queryset=ClientInfo.objects.all(), slug_field='access_id') class Meta: model = Database fields = ('id', 'client_id', 'db_name', 'db_host', 'db_user', 'db_pass', 'db_type') What's wrong? I made everything like in off documentation. Thanks, PS I tried return Database.objects.filter(client_id=client_id) but it doesnt help also -
Django Admin Clear Field When Create New Object
I'm trying to write the BookApp, Everytime i create a new book, its going to load chapter field from previous book in the selection. How can i remove the relationship away but not deleting the content.I have also included pics. #models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=250) def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=500) content = models.TextField() def __str__(self): return self.name class Book(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=500) summary = models.TextField() author = models.ForeignKey(Author) chapter = models.ForeignKey(Chapter) def __str__(self): return self.name` And in the admin.py from django.contrib import admin from books.models import Category, Author, Chapter, Book class BookAdmin(admin.ModelAdmin): list_display = ('category', 'name', 'author', 'chapter') admin.site.register(Category) admin.site.register(Author) admin.site.register(Chapter) admin.site.register(Book, BookAdmin) Here's the imag of problem. Added Book#1 Chapter of Book 1 still exist in loading -
TextField not in range, max range is 128
How can I set the textfield to a larger range? I want to insert a large string from a textarea into a textfield. Error is the range of the textfield is max 128. Code: from django.db import models class Richtingen(models.Model): naam = models.CharField(max_length=100) omschrijving = models.TextField() def __str__(self): return '%s %s' % (self.naam, self.omschrijving) -
How to plug-in action into html form to call specific django url
I've index.html which has a simple form that takes an input field name. When I enter the name, I want to pass this name to django function and perform execution with this name and return results. To do this, this is what I've come up with: index.html: <html> <body> <form action="{% url 'name' %}" method="get"> Enter Name: <input type="text" name="name"/> <br/> <input type="button" value="Submit"> </form> </body> </html> url.py: urlpatterns = [ url(r'^$', index, name='index'), url(r'^name_results/$', get_name_results, name='name'), ] My name() function is doing some sort of operation when 'name' is received and then it sends the HTTPResponse. When executing this code, I don't get anything when I'm entering the 'name' in the form. What am I missing? -
How to reload data after flush in django
<rant> I find migrations to be the most annoying part of Django. </rant> Now, on to business. I can run manage.py flush to purge the database. Now, how do I reload the initial data from the migrations file? If I run manage.py migrate unit I get the following: Operations to perform: Apply all migrations: unit Running migrations: No migrations to apply. My migration file mostly follows the example from the docs, except I modified the 0001 file to run the data loads after schema creation. E.g., class Migration(migrations.Migration): dependencies = [] operations = [ # django makemigration generated schema stuff ... # data creation stuff... migrations.RunPython(models_1_create, models_1_reverse), migrations.RunPython(models_2_create, models_2_reverse), ] -
Django make non persistent field when file uploading
I have a model for Document like : class Document(models.Model): document_name = models.CharField(max_length=64) author = models.ForeignKey(Client, null=False, default=1) size = models.IntegerField(default=0) version = models.CharField(max_length=64) file = models.FileField(upload_to='documents/%Y/%m/%d') but I also want to upload that file. My form looks like class UploadDocumentForm(ModelForm): class Meta: model = Document fields = ('document_name', 'author', 'size', 'version', 'file',) def __init__(self, *args, **kwargs): super(UploadDocumentForm, self).__init__(*args, **kwargs) Now obviously, I want my file to be saved in a folder and not have its own column i nthe db. In db I only want the other data. Problem is, django tries to persist it and crashes with The above exception (table document has no column named file) Is there a way to make file a non persisted field or something? Im following this tutorial, https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html -
How to show the last message of each user to user conversations to keep a chat history?
I'm creating a private user to user chat, in order to chat with someone the connected user has to type the username of the user with whom he wants to talk to on his own url. Now that this system is already built, I want to keep a chat history so that later on I can send notification of chat. To do that I need to get the last message of each conversations and I want to show it on the connected user's own chat profile. Like the image below : Model userComment fields are : recipient, sender, message, sent_at views.py : def inbox(request, username): username = User.objects.get(username=username) connected_user = request.user if username == connected_user: #I'm having the issue on this line users = userComment.objects.filter(Q(client=request.user) | Q(worker=request.user)).order_by(?) else: users = userComment.objects.filter(Q(Q(client=request.user) & Q(worker=username)) | Q(Q(client=username) & Q(worker=request.user))).order_by('sent_at') Question : How can I filter and order my view to do so ? -
Vagrant - How to access postgres server from guest
I have a vagrant box installed, and I added this to the Vagrantfile: config.vm.network "private_network", ip: "192.168.33.33" config.vm.network "forwarded_port", guest: 5432, host: 3333 -
How to receive a out parameter(sys_refcursor) of stored procedure Oracle in Django
I have created a stored procedure usuarios_get , I test it in oracle console and work fine. This is the code of stored procedure create or replace PROCEDURE USUARIOS_GET( text_search in VARCHAR2, usuarios_list out sys_refcursor ) AS --Variables BEGIN open usuarios_list for select * from USUARIO END USUARIOS_GET; The python code is this: with connection.cursor() as cursor: listado = cursor.var(cx_Oracle.CURSOR) l_query = cursor.callproc('usuarios_get', ('',listado)) #in this sentence produces error l_results = l_query[1] The error is the following: NotSupportedError: Variable_TypeByValue(): unhandled data type VariableWrapper I've also tried with other stored procedure with a out parameter number type and modifying in python code listado= cursor.var(cx_Oracle.NUMBER) and I get the same error NotSupportedError: Variable_TypeByValue(): unhandled data type VariableWrapper I work with python 2.7.12 Django 1.10.4 cx_Oracle 5.2.1 Oracle 12c Can any help me with this? Thanks -
DJANGO - NoReverseMatch at / (index;)
I'm try to set the get_absolute_path and I've been trying to define the regex's URL for profile.html page to show the details of user. models.py (app users): from django.core.validators import RegexValidator from django.core.urlresolvers import reverse from django.db import models # Create your models here. class UserGroup(models.Model): GROUP_CHOICE = ( ('Administrator JAM', 'Administrator JAM'), ('Supervisors', 'Supervisors'), ('Agents', 'Agents'), ) name = models.CharField('User Group Name', max_length=50, unique=True, choices=GROUP_CHOICE) slug = models.SlugField('Group ID', unique=True) def __str__(self): return self.name class Meta: verbose_name = "User's Group" verbose_name_plural = "User's Groups" ordering = ['name'] # ordenando por nome e depois por ultima modificação class User(models.Model): name = models.CharField('Name', max_length=100) username_regex = RegexValidator(regex=r'^[\w_-]{5,50}$', message='The username must be consist only of letters and numbers. From 5 up to 15 characters allowed.') username = models.CharField('Username', validators=[username_regex], max_length=50, unique=True) slug = models.SlugField('User ID', max_length=50) user_group = models.ForeignKey('users.UserGroup', verbose_name='User Group') is_active = models.BooleanField('Active', default=True, choices=((True, 'Active'), (False, 'Deactive'))) def __str__(self): return self.name def get_absolute_url(self): return reverse('profile_agent', kwargs={'slug': self.slug}) class Meta: verbose_name = 'User' verbose_name_plural = 'Users' ordering = ['name', 'user_group', 'is_active'] urls.py (from root): urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^edit_profile/$', views.edit_profile, name="edit_profile"), url(r'^inbox/$', views.inbox, name="inbox"), url(r'^profile/', include('users.urls', namespace='users')) ] urls.py (from app users): from . import views from … -
How to replace get_profile() in Django 1.10
I have upgraded from a much older version to Django 1.10 and I have probably about 30 calls to get_profile() throughout my entire codebase. I have read on SO and the docs, but I am still not understanding how to replace this functionality now that get_profile() is deprecated. snippet of models.py class MyProfile(UserenaBaseProfile): user = models.OneToOneField(User, unique=True, verbose_name=_('user'), related_name='my_profile') storename=models.CharField(null=True, blank=True, max_length=20) So how would I replace extra_context['profile'] = user.get_profile() extra_context['profile'] = user.my_profile ? -
Django Apache and WSGI setup not finding urls?
I am setting up Django on a VPS with Apache and and modwsgi and have this setup for 000-default.conf, <VirtualHost *:80> . . . Alias /static /home/user/myproject/static <Directory /home/user/myproject/static> Require all granted </Directory> <Directory /home/user/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/user/myproject WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myproject/wsgi.py but when I access my www.myproject.com I get this error Not Found The requested URL / was not found on this server. Apache/2.4.18 (Ubuntu) Server at www.myproject.com Port 80 What could be wrong? -
Understanding this Django Search Functionality
I have recently implemented a Search functionality for Django Web application (it works just fine). However, I do not fully understand the workings of the code. Can you please explain step-by-step what is going on - more specifically; How does "get_queryset" & "get_contest_data" (views.py) work together? How does the search request (from template) know to go to "get_queryset"? What is return qs? View: from django.db.models import Q class ProductListView(ListView): model = Product queryset = Product.objects.all() def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) context["now"] = timezone.now() context["query"] = self.request.GET.get("q") #None return context def get_queryset(self, *args, **kwargs): qs = super(ProductListView, self).get_queryset(*args, **kwargs) query = self.request.GET.get("q") if query: qs = self.model.objects.filter( Q(title__icontains=query) | Q(description__icontains=query) ) try: qs2 = self.model.objects.filter( Q(price=query) ) qs = (qs | qs2).distinct() except: pass return qs Template <form class="navbar-form navbar-left" method="GET" role="search" action='{% url "products" %}'> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" name="q"> </div> </form> -
Django- Admin.py, number in exam
I have a problem with creating a class in admin.py. Especially with extra. I need to connect this number with a number in models.py multi or count_of_multi_choice but I don't know how. Thank you for your reply. admin.py models.py -
How can I share a template to angularjs in a django project?
Suppose I have a template directory. And I am serving the a index.html from django. I thought that I'll use angularjs to route in frontend. For that reason, I need to include template. But when I am trying to include this, it's showing errors on console (404). -
Static CSS file not loading in Django framework
I'm running on localhost but stylesheet isn't working Here is my project setup: -main -main -home -templates -home -index.html -static -css -style.css My settings.py: STATICFILES_DIR = [ "/static/", ] STATIC_URL = '/static/' index.html: {% load staticfiles %} <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>My Home Page</title> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> </head> <body> <p>My Content</p> </body> </html> Here is what my server outputs: "GET /static/css/style.css HTTP/1.1" 404 1652 What is wrong? -
save() prohibited to prevent data loss due to unsaved related object Django 1.10
Ok, so after some searching, non of the related question adress my specific problem as far as I can tell. I obviously don't understand if they do, so I apologize for any redundacy. This is my traceback: Traceback (most recent call last): File "csvimport.py", line 79, in f.save() File "/home/blake/django_/venv/lib/python3.5/site->packages/django/db/models/base.py", line 752, in save "unsaved related object '%s'." % field.name ValueError: save() prohibited to prevent data loss due to unsaved related >object 'aircraft'. This is the script in question: http://pastebin.com/Jks0HgEr These are my models: http://pastebin.com/uGUqckqS I can't tell why the function assignAircraft() isn't saving the Aircraft.aircraft_type object when its being called on line 56 Strangely though, the first instance of row[1] is being saved to the Aircraft model. Also, any refinements / pep8 suggestions are welcome. -
Create graphene mutations accessible to logged out users (Django)
I am implementing a web application that uses a back-end implemented in Django with the API written in graphene GQL. I need to provide login / logout functionality. These should be (ideally) implemented as mutations. The login mutation should be able to operate without an authentication token (of course, since the user is not yet logged in). I do not want to disable csrf checks for the whole api (via csrf_exempt on the graphene view). Is there a way to disable csrf checks only for one mutation (login in my case) ? -
Reverse for '' with arguments '' and keyword arguments '{}' not found and keyword arguments '{'pid': ''}'
Im trying to create view in which I can save templates as draft and Update the draft if its value is 1 or otherwise save a new document I have the following Url configuration url(r'^addprescription/(?P<pid>\d+)/$', views.viewtemplate, name='newtemplate') for this view def viewtemplate(request, patid): patient = Patient.objects.get(patientid=patid) #form = templateform(request.POST) if request.method == "POST": if presciptiontemplates.draft == 1: form = newpatientform(request.POST, instance=patient) if form.is_valid(): form = form.save(commit=False) form.patientid = patid form.save() messages.success(request, 'Form submission successful') return redirect('index') else: form = templateform(request.POST) if form.is_valid(): form = form.save(commit=False) form.patientid = patid form.save() return redirect('index') else: form = templateform() return render(request, 'presapp/prescription.html', {'form': form})` Template <a class="waves-effect waves-light btn right" href="{% url 'newtemplate' pid=patientid%} " >Add new </a> Im getting the error Reverse for 'newtemplate' with arguments '()' and keyword arguments '{'pid': ''}' not found. 1 pattern(s) tried: ['addprescription/(?P\d+)/$'] Django 1.10 Python 3.5 Windows 7 -
Command "python setup.py egg_info" failed with error code 1 fandjango
I am trying to install fandjango by using: pip install fandjango However I get the error: Collecting fandjango Using cached fandjango-4.2.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "C:\Users\Apaar\AppData\Local\Temp\pip-build-0j7g1eqn\fandjango\setup.py", line 5, in execfile('fandjango/version.py') NameError: name 'execfile' is not defined ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\Apaar\AppData\Local\Temp\pip-build-0j7g1eqn\fandjango\ Any help would be greatly appreciated