Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SELECT typarray FROM pg_type WHERE typname = 'citext'
SELECT typarray FROM pg_type WHERE typname = 'citext' Why I am getting this query in django debug panel and what does it mean? Whenever I navigate to the new page, this query gets run as 1st then all others, same thing in the python shell using connection.queries command. I am using django 1.11 and postgres 9.6. -
Django Rest Framework AttributeError 'function' object has no attribute 'model' in router.register
I try my first Django API using Django Rest Framework. Everything was fine, but I change something and stuck in this AttributeError and don't understand what to do. my code looks like in tutorial and it is half past 4 am, I really need help. so, this is the callback python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/dev/test/demo/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check for pattern in self.url_patterns: File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/dev/test/demo/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dev/test/demo/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, … -
Processing payment in dynamic form wizard
In django SessionWizard view how would I go about dynamically adding two forms, representing checkout and a receipt view, if the user chooses an option in the previous form that marks it is a paid item. I tried extending the form list in post but this causes nothing to be rendered. Moreover, since this is session based is this not insecure, even using braintree, since it's dealing with card numbers, paypal, etcetera. I would like to achieve a wizard, for a streamlined flow, of choosing a plan -> filling out form -> if paid -> checkout / receipt. -
Django dynamic verbose name
I'm struggling to think about how to achieve this. What I want to do is have a series of questions (to represent a Likert table) in a CharField object like so: for a in range(1, 11): locals()['ATL' + str(a)] = models.PositiveIntegerField( choices=[ [1, 'Disagree Completely'], [2, 'Disagree Strongly'], [3, 'Disagree'], [4, 'Neutral'], [5, 'Agree'], [5, 'Agree Strongly'], [7, 'Agree Completely'], ], widget=widgets.RadioSelectHorizontal(), verbose_name = Constants.ATL_qu_list[a-1]) del a And then change the verbose name for the question depending on the question number (again, I know I'm not supposed to be using locals() to store variables). Is there an easier way of achieving a dynamic label though? Thanks! -
Django Error Reverse for 'url' not found. 'url is not a valid view function or pattern name
I'm working on Django and in a trouble with removing old urls. I've got seven pages(urls) in my present program but decided to make it simpler with only three pages(urls). Then I tried to remove them just by comment-out, but it just comes out with the error like Reverse for 'url name' not found. 'url name' is not a valid view function or pattern name. I'm not getting those unnecessary urls set in other pages, so it should be deleted without any problem. Here is a snap shot to go more in details. error image A page link is showing as an error origin, but the page is actually nothing to do with the deleted urls. Need your help! Thanks! -
How do I get get a model objects own ID for limit_choices_to?
How do I limit choices of a ForeignKey to Objects which have a ForeignKey to an object I also have a ForeignKey too? class ExtendedProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='extended_profile') dob = models.DateField(null=True, blank=True, verbose_name="date of birth") prefered_profile = models.ForeignKey('Trainer', on_delete=models.SET_NULL, null=True, blank=False, related_name='main_profiles', limit_choices_to={ 'owner' : ____ }) def __str__(self): return self.user.username def create_user_profile(sender, instance, created, **kwargs): if created: ExtendedProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) ExtendedProfile is an extension Django's own User Model so has a OneToOneField type ForeignKey. Trainer is a different model of a profile, where there may be more than one Trainer with the same ForeignKey (field name 'owner') to User. I'm basically trying to ensure that 'prefered_profile' can only be objects owned by the same user as ExtendedProfile is... How do I get a value of self on a model? -
Create form set of arbitrary form types in Django forms
I know given a form type, I can create a form set allowing me to create a set of forms based on the given form type. However, this doesn't quite solve my problem. Let's say I have a portal for a fast food place where the user can add items and after they choose the item, we spawn forms for extra fields. For instance, if they add a item and choose food type "Drinks", then we give them options to add ice or get it go. If they choose hot food, we ask if they like it spicy. I'm struggling to accomplish this with Django forms. If I had a super form that included all the options regardless of item type, I could accomplish this by creating a FormSet but that's not what we're doing. I could accomplish creating new forms and dynamically updating every item as user changes the item type using the following code: In the HTML template, I add the following to create templates. {% for food_order_form in food_order_form_set %} <script id="food-order-template-{{ food_order_form.name }}" type="text/x-custom-template"> {{ food_order_form.form.as_p }} </script> {% endfor %} Then I have JavaScript code that creates these forms based on a global variable: var … -
Django-filter AND Django-tables2 CheckBoxColumn compatibility
This is my first post. I genuinely searched for an answer and couldn't find it, but if it is out there please direct me towards it. I am using Django-filter with my model and it works great, my table displays and I can filter by certain column data. I want to have a checkboxcolumn in my returned table via Django-filter, then select rows with a checkbox, and then do something with these rows. From the tutorials/examples, all I see is the checkboxcolumn implemented with a basic table via Django-tables2. Can checkboxcolumn be implemented along with returned table via Django-filter? Or, do I need to build my own model filter in order to use the checkboxcolumn for a basic table? Currently my code works fine, so unless crucial, I will not post it yet. Thanks -
django oscar paypal redirect
I am using Django Oscar Paypal for payment. I am having an issue with redirecting back to my website on the production mode. I have successfully set up in the development mode and I have tried two different IP address for runserver : 127.0.0.1:8000 and 192.168.1.102:8000 -> both worked corrected and redirected to whatever server I was running. I turned off Sandbox mode and I have a website that has https:// working correctly. I try to make a payment on mywebsite.com/ but it redirects to https://192.168.1.102:8000/checkout/paypal/preview/13/?token=******* when I am redirected to paypal website for payment and click on Continue. (This happens for cancelling as well). I have checked the views in the paypal app and it has 'reverse' code written correctly. If I paste /checkout/paypal/preview/13/?token=******* part after mywebsite.com/, it seems to be working correctly. Is there a way to redirect back to mywebsite.com/ Many Thanks Kyu -
How to get a Django migration involving a unique index applied across foreign keys to go backwards?
Today I was tasked with fixing a stack of migrations so they can go fully forwards and backwards from scratch, without relying on starting from a database dump from production. I ran across this. class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('content', '0038_merge'), ] operations = [ migrations.CreateModel( name='UserRoles', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('role', models.CharField(max_length=100, choices=[(b'editor', b'Editor Role'), (b'read_only', b'Read Only'), (b'writer', b'Writer Role')])), ('site', models.ForeignKey(related_name='site', to='content.Site')), ('user', models.ForeignKey(related_name='user_site_roles', to=settings.AUTH_USER_MODEL)), ], ), migrations.AlterUniqueTogether( name='userroles', unique_together=set([('user', 'site')]), ), ] Forwards and backwards, here is the SQL it generates. BEGIN; CREATE TABLE `content_userroles` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `role` varchar(100) NOT NULL, `site_id` integer NOT NULL, `user_id` integer NOT NULL); ALTER TABLE `content_userroles` ADD CONSTRAINT `content_userroles_user_id_798e435c65731cb9_uniq` UNIQUE (`user_id`, `site_id`); ALTER TABLE `content_userroles` ADD CONSTRAINT `content_userroles_site_id_3eb32f440311bcb0_fk_sites_id` FOREIGN KEY (`site_id`) REFERENCES `sites` (`id`); ALTER TABLE `content_userroles` ADD CONSTRAINT `content_userroles_user_id_6a54f536e78383a8_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); COMMIT; BEGIN; ALTER TABLE `content_userroles` DROP INDEX `content_userroles_user_id_798e435c65731cb9_uniq`; DROP TABLE `content_userroles` CASCADE; COMMIT; When it attempts to drop the unique index, it runs across the error: Cannot drop index 'content_userroles_user_id_798e435c65731cb9_uniq': needed in a foreign key constraint Is this a Django bug? Is there a workaround to allow what looks like a simple migration to be reversible? … -
Best configuration for Django staticfiles
In my Django project I have a static folder in the root of the project (near manage.py), so in settings.py, in order to find this static files I have: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] How do I have to configure STATIC_ROOT? Now I think about: STATIC_ROOT = os.path.join(BASE_DIR, 'static/') But when I run collectstatic it fails, static files are loaded but not in the admin site. How can I solve this issue? -
How to generate a text webpage after uploading an xlsx file in Django?
I have a field where users upload an xlsx file In Django, however, im having trouble getting Django to return a simple text-based webpage from users uploading that xlsx file. Basically, I need Django to generate text from the cells of the xlsx file they uploaded. Im trying to use openpyxl to do this. How do I get Django to generate a new page with the results of the xlsx file after my script runs over it? Do I need to create a new template that redirects to it once the user submits the uploaded xlsx file? Here's an example. # views.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from .forms import UploadForm import openpyxl def index2(request): if request.method != 'POST': form = UploadForm() else: form = UploadForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() file = request.FILES['fileobj'] wb = openpyxl.load_workbook(file) sheet = wb.get_sheet_by_name('Sheet1') # script that runs overs the sheet here... return HttpResponseRedirect(reverse('webpage with results')) context = {'form': form} return render(request, 'upload/upload_page.html', context) -
How to convert a dynamic Meteor html to pdf in Django (or Python)?
I tried the following script and got a blank PDF. Are there any other tools I could try? Thanks! os.system("wkhtmltopdf --dpi 300 -s letter {a dynamic Meteor website} test.pdf") -
Links based off slugs giving error
I have this link with url: <a href="{% url 'listings:listing_detail' list.l_slug %}" class="btn btn-primary">See More</a> It is directing it to this url pattern for my app: from django.conf.urls import url from listings import views app_name = 'listings' urlpatterns = [ url(r'^$',views.UniversityListView.as_view(),name='universities'), url(r'^/(?P<name_initials>\w+)$',views.ListingView.as_view(),name='listing_detail'), ] Here are the project url patterns to go along with it: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomeView.as_view(),name='index'), url(r'^(?P<u_slug>[-\w]+)/$',views.UniversityHomePageView.as_view(),name='university_homepage'), url(r'^(?P<u_slug>[-\w]+)/',include('listings.urls',namespace='listings')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) However I am getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'listing_detail' with arguments '('stafford-apartments',)' not found. 1 pattern(s) tried: ['(?P<u_slug>[-\\w]+)//(?P<name_initials>\\w+)$'] Django: 1.11 -
How to use a custom renderer based on request params?
Goal: Have every endpoint taking export=csv in the params to output a CSV file instead of Json data by using a custom Renderer and not changing every View's code Setting another Renderer seemed like the simplest solution: class MyView(ListAPIView): renderer_classes = (BrowsableAPIRenderer, CSVRenderer) pagination_class = StandardPagination serializer_class = MySerializer ... and on the CSVRenderer check if the url contains export=csv, but this yields plain text data in CSV format and not a file. Removing the BrowsableAPIRenderer would work but I still need to have the endpoint working without the export=csv. Is there a way to have something checking the url before the renderers are called? Suggestions are welcome if theres be a better way to achieve this. -
how to pass an error message from django admin filter to change list
On my change list admin page, I made a custom filter. I want to be able to send an error/warning message back to the user when a choice is wrong. (I know that filter choices by default are never wrong but I've converted the select drop down into a text input and therefore some values could be invalid) Any idea how I can send an error message from a filter? Here is what I tried: #filter.py class MyFilter(SimpleListFilter): title = ugettext_lazy('Score') parameter_name = 'Score' def lookups(self, request, model_admin): return [('0.9', 's>=0.9')] def queryset(self, request, queryset): try: something except Exception as ex: request.error_msg = 'xxx' return queryset # admin.py @admin.register(SomeModel) class MyAdmin(CustomAdmin): list_filter = (MyFilter,) def get_queryset(self, request): if hasattr(request, 'error_msg'): print request.error_msg to send "error_msg" to the change_list admin template and display it. Another idea is to redirect but I don't think it's possible from the filter. -
how to create dropdown menu in django
I'm new to django and would like to create a drop down menu for options. I'm confused as to what I should include in my forms.py and how to call that form on my index.html. My forms.py from django import forms class MyModel2(forms.Form): class Meta: model = MyModel fields = ['color'] My index.html <form method="POST" action = "">{% csrf_token %} <p>Choose color</p> {{ form.color}} <br><br> <input type="submit" value="Submit!"/> </form> My models.py from __future__ import unicode_literals from django.db import models COLOR_CHOICES = ( ('green','GREEN'), ('blue', 'BLUE'), ('red','RED'), ('orange','ORANGE'), ('black','BLACK'), ) class MyModel(models.Model): color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green') Thank you! -
Why doesn't my checklist get sent as a POST
I have the following template, which my button is working to send my select options to a POST and then switch URLs. However, I have a collection of check boxes the user selects and I want to capture the report_id of each check box. I'm on the last step of the project for my class with very little direction and struggling to get this form to work as intended. <form action = "{% url 'submitted' %}" form method = "POST"> {% csrf_token %} {{ form.as_p}} <div class="container"> <div class="row"> <div class="col"> <label for="accesslevel"><h3>Access Level</h3></label> <select name ="accesslevelid" class="form-control my_select" id="accesslevelid"> <option value=""> Please select your access level </option> <option value="7"> Facility </option> <option value="5"> Division </option> <option value = "3"> Corporate </option> <option value = "6"> Market </option> <option value = "4"> Group </option> </select> </div> <div class="col"> <label for="phi"><h3>PHI</h3></label> <select class="form-control my_select" id="phi" name = "phi" > <option value = ""> Please select if you need access to PHI data </option> <option value = "0"> No </option> <option value = "1"> Yes </option> </select> </div> </div> <div class="row"> <div class="container"> <div class="row"> <div class="col"> </br> </div> </div> <div class = "container"> <div class="jumbotron"> <div class="container"> <h1 class="jumbotron-heading">Available Application List</h1></br> … -
Django ORM Annotate current company to users queryset
I have the following model: class UserCompany(models.Model): user = models.ForeignKey(User) company_name = models.CharField(max_length=200) department = models.CharField(max_length=200) position = models.CharField(max_length=200) start_date = models.DateField() end_date = models.DateField(null=True, blank=True) Single user can have multiple UserCompany objects. Now I want to query all users and annotate the queryset with company_name, department, position and start_date where the end_date is null. If there are more than one UserCompany object without end_date I don't care, any of them is fine. I tried with raw sql subqueries like below and it seems to work, but I wonder if there is more efficient way to do this, or write this without raw sql. I know there is Subquery expression in Django 1.11+ but the version of Django I am using doesn't support it and I don't want to upgrade at this moment. My solution: from django.db.models.expressions import RawSQL def create_rawSQL(field): return RawSQL( "SELECT `myapp_usercompany`.`%s` FROM `myapp_usercompany` WHERE `myapp_usercompany`.`user_id` = `auth_user`.`id` AND `myapp_usercompany`.`end_date` IS NULL LIMIT 1" % field, () ) users = User.objects.all().annotate( company_name=create_rawSQL('company_name'), position=create_rawSQL('position'), department=create_rawSQL('department'), start_date=create_rawSQL('start_date') ) I am using Django 1.9.8, Python 2.7.13 and MySQL. Thanks! -
Adding Css Style to Table in djano with django_tables2
I'm very new to Django trying to add to a css style to a table when {% render_table table %} is being run. The code looks as following: views.py: def myTable(request): table = myDataTable.objects.all() filter = request.GET.get('q') startDate = request.GET.get('sd') endDate = request.GET.get('ed') if mail: table = table.filter(Q(filter__icontains=filter) & Q(evaluation_date__range=[startDate, endDate])).distinct() else: table = table.filter(Q(evaluation_date__range=[startDate, endDate])).distinct() table = TableView(table) RequestConfig(request).configure(table) return render(request, 'myapp/myTable.html', {'table': table}) tables.py: class TableView(tables.Table): class Meta: model = myDataTable template = 'django_tables2/bootstrap.html' myApp.html {% load staticfiles %} {% load render_table from django_tables2 %} .... <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"> .... <body> {% render_table table %} In project/static/css/ i have custom style file customstyle.css file, but there is no way to make the rendered table use that style. Could you please help me? Thank you :) -
Data shown in admin panel not correct in Django
I have a Restaurant model: class Restaurant(models.Model): #others A Food model is: class Food(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name="res") #others And a Review model class Review(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='rest') food = models.ForeignKey(Food, on_delete=models.CASCADE, related_name='foo') #others The problem i am having is:- When I try to add a Review through admin panel and select restaurant1, I don't get the foods only from restaurant1 but from all restaurants. -
Traceback in image_cropping/utils.py
python manage.py load_users I have Win10. Others commands such as "load_page", "load_cities" work perfectly. Except these two "load_users", "load_new_announcement" - because of images. I don't know what to do. P.S. All works fine in Ubuntu. -
possible to add additional field into all querysets? django
I have a querysets in a model for example class ModelA(models.Model): name = models.Charfield(max_length=256) ageMin = models.IntegerField(null=True, blank=True) ageMax = models.IntegerField(null=True, blank=True) def age(self): low = self.ageMin high = self.ageMax if low and high: return str(low) + ' - ' + str(high) if low: return str(low) if high: return str(high) let's say I have a queryset to get all return of ModelA I actually want to add a field into all queryset such as a field named age_gap which is the def age from the model itself so each queryset will also have an extra field named gap_gap not just name, ageMin, ageMax I tried something like the following but not working though. all_q = ModelA.objects.filter() qs = map(lambda x: x.update({'age_gap': x.age()}), all_q) the above doesn't work so I thought of trying something like for q in all_q: q['age_gap'] = q.age() of course this gives me error too Can someone please give me a hand on how this can be done? Thanks in advance -
django admin - how to get the current url parameters in python
Here I made an example of what I have in my admin.py: @admin.register(Car) class CarAdmin(CustomAdmin): list_display = ('get_color',) def get_color(self, obj): return mark_safe('<a href="/admin/myapp/car/?color={}">{}</a>'.format(obj.color, obj.color)) I have produced a link that can be used to display cars with a specific color. Let's say the page is currently showing cars that cost less than $20k and I want this link to preserve the current filter. Any ideas how to do that? Maybe there is a way to get the current url from python. Note that I know I can write a javascript to modify the links after the page is loaded, but that is a terrible solution. -
Django lookup multiple models reusing querysets
Let's say I want to get a list of houses where the owner's car has a seat that's red. I could do it like this: queryset.filter(owner__cars__seats__color='red') However, I would like to reuse the filter of getting cars that have a red seat, so I have a custom Queryset on Cars. class CarsQuerySet(models.QuerySet): def with_red_seats(self): return self.filter(seats__color='red') Is there a way to do reuse the "with_red_seats" filter on the first query? Something like this, which obiously doesn't work: queryset.filter(owner__cars__with_red_seats)