Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) -
Migrations don't create new tables
I have models.py in a Django app that has a few models that I have the corresponding tables for in MySQL, and others that I do not. How do I get Django to create the tables for the models that don't have them? I tried makemigrations and migrate, but they were not delivered. But then again django.db.utils.ProgrammingError: (1146, "Table 'test_vcc.polls_choice' doesn't exist") What am I doing wrong? I am using Django 1.11.7, Python 3.6.3 on MySQL 5.7 -
Django message catalog app
I am looking for an app or a functionality in Django that has messages by number. Eg. Msg 10 - Wrong Password Msg 23 - Congratulations Usage on a view {'returnMsg': messageapp.getCatalog(10)} This kind of stuff... and also supporting translation so the message can have one text per language. I have looked all over Django website and on google, but found nothing like this. If that doesn't exists, than I will go ahead and create some app that does that, but I would rather use something that is there. -
Querying in solr using Django Haystack but not models
I am trying to create a search engine on a cloud machine. I have used solr to index. And I am using Django and haystack for front end and querying. I have done the following till now: 1. Collected data from internet in a Json file 2. Indexed that Json File on Solr-7.1.0 3. Installed Django and Haystack. Edited settings.py. Made connection to solr. The next step is to create a single webpage for searching. Following is what I got from the "Django by example" book for querying: def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all() # count total results total_results = results.count() return render(request,'blog/post/search.html',{'form': form,'cd': cd,'results': results,'total_results': total_results}) The problem is: I don't have any databases (and therefore no models) in my application. Indexing was done directly on solr by giving it a json file. But the following line of code requires a model for querying on the indexed code. SearchQuerySet().models(Post).filter(content=cd['query']).load_all() Is there a way to search the index in solr when there are no models? -
How to make every field able to process a request with several options in Django REST?
Suppose I own a store, and there is a database table with information about everything I sell; it basically records what I sold and to whom I sold it. I use Django REST to interface with said database, and I can access the table data via /rest/purchases. I would like to filter those purchases by client, but I'd also like to be able to pass in an array of clients' IDs and get all the purchases they made. Here's the catch: I'm well aware that this can be easily achieved, either by creating a custom filter class inside the viewset class for this specific endpoint or by overriding the get_queryset method. The thing is that I want this functionality to be available for ALL fields in ALL my viewsets, and if I create another project later, I'd also want this functionality in all its viewsets and fields. So, changing the get_queryset method or adding custom filter_classes is not a viable option, because it takes up too much time. Bottom line: is there a way to create this custom filter and inject it in all field of my project? Studying the DRF, I got to where the filters for each field … -
How to save data in a DB field that is not listed as part of a DJango CreateView
I have the following CreateView where I am trying to Mstrstorehead-contactemail with the email address of the person who has logged in. The problem is that contactemail is not listed as one of the fields to be displayed on the CreateView form (which is MstrstoreheadCreate) How can I get this field assigned? views.py class MstrstoreheadCreate(CreateView): model = Mstrstorehead fields = ['companyname', 'taxeinno', 'companyname', 'abanumber', 'businesstypeid', 'ourmission', 'contactsalutationid', 'contactfirstname', 'contactlastname', 'contactofficephoneno', 'contactcellphoneno' ] template_name_suffix = '_mstr_create_form' def form_valid(self, form): mhead = form.save(commit=False) mhead.contactemail = self.request.user.email << contactemail is part of the model but NOT part of the fields used in CreateView return super(MstrstoreheadCreate, self).form_valid(form) TIA -
CSS font only works in some Django templates extended from same base
I'm in the middle of creating a fairly complex site using Django, and I've noticed a weird problem. All of my templates extend the same base template (base.html). That base template looks (something) like this: {% load staticfiles %} <html> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'css/fonts.css' %}"> <link rel="stylesheet" href="{% static 'css/webStyleSheet.css' %}"> {% block head %} {% endblock %} </head> <body> <div class="wrapper"> {% block header %} <div class="header"> <h1><a href="/">Title</a></h1> <ul class="nav-bar"> <!-- nav bar content here etc etc--> </div> {% endblock %} </div> </body> </html> <!-- js relevant to the nav bar etc etc --> {% block script %} {% endblock %} My fonts.css file declares my font-faces, for example: /* latin */ @font-face { font-family: 'Overpass Mono'; font-style: normal; font-weight: 400; src: local('Overpass Mono Regular'), local('OverpassMono-Regular'), url('../fonts/OverpassMono-Regular.woff') format('woff'), url('../fonts/OverpassMono-Regular.ttf') format('truetype'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215; } And in my webStyleSheet.css I implement those fonts like so: :root { --font-secondary: 'Overpass Mono', monospace; } /*the class I use for the nav-bar elements*/ .menu-button { font-family: var(--font-secondary); } As I said, I extend this base in all of my templates. The problem arises in that on some of …