Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Override Radio Button Option template
I would like to override template option_template_name in a ChoiceWidget in Django 1.9 to insert attribute disable to some choices dynamically. For example, I've overridden RadioSelect (which extends ChoiceWidget) like this : class CustomRadioSelect(forms.RadioSelect): option_template_name = 'options.html' template_name = 'template.html' Then I use it in my form : class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['my_field_with_radio_buttons'] = forms.ChoiceField( required=False, widget=CustomRadioSelect, choices=my_choices, ) But the template of the options seems to be not overrided. Some ideas ? -
Maintain path redirect after signup in Django
A user needs to be have an account in order to use the service. After the user clicks on the link that was sent to them and if they do not have an account, they are prompted to register for one. However, after they signup, they need to be redirected back to the original link that they clicked on. I am not sure how to go about doing this because I am unfamiliar with class based views in Django. I have the following Class for the Signup Form in views.py: class SignUpView(bracesviews.AnonymousRequiredMixin, bracesviews.FormValidMessageMixin, generic.CreateView): form_class = forms.SignupForm model = User template_name = 'accounts/signup.html' success_url = reverse_lazy('home') form_valid_message = "You're signed up!" def form_valid(self, form): r = super(SignUpView, self).form_valid(form) username = form.cleaned_data["email"] password = form.cleaned_data["password1"] user = auth.authenticate(email=username, password=password) auth.login(self.request, user) return r Then, in forms.py I have the following: class SignupForm(authtoolsforms.UserCreationForm): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.fields["email"].widget.input_type = "email" # ugly hack self.helper.layout = Layout( Field('type', placeholder='recruiter'), Field('email', placeholder="Enter Email", autofocus=""), Field('name', placeholder="Enter Full Name"), Field('password1', placeholder="Enter Password"), Field('password2', placeholder="Re-enter Password"), Submit('sign_up', 'Sign up', css_class="btn-warning"), ) I was thinking about using self.request.path in a function to get the path after "?next=" in the url as … -
Programming the configurator in django, generate PDF, survey
Welcome friends I would like to build a configurator using Django. The configurator uses form fields like input, select elements, checkbox and radio. Based on form fields, it generates PDF. Send an automatic PDF file by email. Action similar to the survey. Can you recommend me something? Anything: courses, books, source code, tutorials, posts, examples. Any Help would be appreciated. -
Edit multiple instances in Django admin
Is there a way to edit multiple instances in a Django admin? Currently I have a list view, and have to click through each instance in order to change the individual instance. How can I have it list all of the instances as editable fields? Here's my current admin config: from django.contrib import admin from .models import Person class PersonAdmin(admin.ModelAdmin): list_display = ( 'has_signed_up', 'timestamp_signed_up', 'position', 'email', ) admin.site.register(Person, PersonAdmin) -
Database table for bus booking website
I'm creating a bus booking website using Django. I'm stuck at what the database tables should look like. So far I've created the displayed tables, I'm very poor with databases so please mention foreign keys and primary keys when answering. Also, I'm stuck on how to actually book seats in Django, like what will be the code in the background and what other packages should I use. Thanks. Table- Route: Columns - route_id (primary key), location_from, location_to, route_name, Table - Bus: Columns - Bus_id(primary key), type_of_bus, bus_registration, capacity, bus_number, route (foreign key) Also I'm using the default sqlite database that comes with django. Is it good enough to build this kind of website or do I need to change? This website is just a project and will never go into production phase. -
Django GEO MySQL query error `'WKTAdapter' object has no attribute 'translate'`
I have model: from django.contrib.gis.db import models class MyModel(models.Model): poly = models.PolygonField() Django settings: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.mysql', ... And when i try to filter MyModel by poly field such as: from django.contrib.gis.geos import Point MyModel.objects.filter(poly__contains=Point(23.23452, 45.123444)) I got error AttributeError: 'WKTAdapter' object has no attribute 'translate' As you can see i use Python 3.6.0, Django==1.10.6, PyMySQL==0.7.11, mysqlclient==1.3.10. And MySQL is 5.7.16 Is there anyway to make it work? Or i need to extrack all poly values and then process it in pure Python? Full traceback: Traceback (most recent call last): File "<input>", line 1, in <module> File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/models/query.py", line 232, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/models/query.py", line 256, in __iter__ self._fetch_all() File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/models/query.py", line 1087, in _fetch_all self._result_cache = list(self.iterator()) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/models/query.py", line 54, in __iter__ results = compiler.execute_sql() File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 835, in execute_sql cursor.execute(sql, params) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 110, in execute return self.cursor.execute(query, args) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/pymysql/cursors.py", line 164, in execute query = self.mogrify(query, args) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/pymysql/cursors.py", line 143, in mogrify query = query % self._escape_args(args, conn) File "/Users/ailove/Work/breeders/python3/lib/python3.6/site-packages/pymysql/cursors.py", line 118, in _escape_args … -
How to Download Django Database Dump from Amazon Elastic Beanstalk?
I have a Django application on Amazon Elastic Beanstalk that has been working for two years. I am trying to upgrade it and make some fundamental changes to it. In order to make sure I do not loose anything, I used the following command to create a database dump: ./manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json However, I do not know how I can download the database dump file from the Elastic Beanstalk instance to my local computer. Any help is highly appreciated. -
How to test views that use post request in django?
here's my view (simplified): @login_required(login_url='/try_again') def change_bar(request): foo_id = request.POST['fid'] bar_id = request.POST['bid'] foo = models.Foo.objects.get(id=foo_id) if foo.value > 42: bar = models.Bar.objects.get(id=bar_id) bar.value = foo.value bar.save() return other_view(request) Now I'd like to check if this view works properly (in this simplified model, if Bar instance changes value when it should). How do I go about it? -
formset() is not a function, typeerror using jquery.formset.js
I'm using jquery.formset.js to try and dynamically add and delete rows to my formset. https://github.com/elo80ka/django-dynamic-formset I'm getting an error in Chrome developer tools: Uncaught TypeError: $(...).formset is not a function(…) And I don't get why... Here is what my template looks like with my script defined at the bottom and link to jquery.formset.js. {% extends 'project/base.html' %} {% block title %}...{% endblock %} {% load staticfiles %} {% block content %} <form id="time-form" method="POST" action="" class="dynamic-form" enctype="multipart/form-data">{% csrf_token %} <div style="overflow-x:auto; padding-bottom:0;"> <table id="timesheet" class="tables"> <tbody> <tr class="table-header"> <th>Date</th> <th colspan="2">Description</th> </tr> {{ time_formset.management_form }} {% for form in time_formset %} <tr class="formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% if forloop.last %} {% if form.instance.pk %}<td>{{ form.DELETE }}</td>{% endif %} {% endif %} {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </br> <input type = "submit" id = "save" value = "Save"> </form> <script type="text/javascript" src='/media/jquery.formset.js'></script> <script> $(function() { //ERROR RAISED HERE// $('#time-form div table#timesheet tbody tr.formset_row').formset({ prefix: '{{ time_formset.prefix }}' … -
Validate Uniqueness Within Grandparent with ManyToManyField
I'm trying to validate a model with a ManyToManyField pointed at a parent model to be unique within a grandparent model. It's fine if different grandparents have grandchildren of the same name, but a grandparent may not have two grandchildren of the same name. This question Discusses a solution if the relationships are ForignKeys, but that doesn't work here. The GrandChild has to be saved before I can reference the parents to test to see if it's unique within a GrandParent. Since the Parents can't be attached until the GrandChild exists, how can the uniqueness of a GrandChild be validated against the GrandParent? class GrandParent(models.Model): name = models.CharField(max_length=255) class Parent(models.Model): name = models.CharField(max_length=255) grandparent = models.ForeignKey(GrandParent) class Meta: unique_together('name', 'GrandParent') class GrandChild(models.Model): name = models.CharField(max_length=255) parents = models.ManyToManyField(Parent) def validate_unique(self, exclude=None): # validate that GrandChild is unique within a given GrandParent -
socket access in forbidden way for its access permision in django
I tries running the command "python manage.py runserver" in django for creating the local server it showed me the following error "[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions in django " -
Value of constant not affecting
I have installed new app(tastypie-swagger) for Django 1.9. For this I have to define TASTYPIE_SWAGGER_API_MODULE . Even after I defined the value in the settings.py file I am getting the error saying that I must defined the constant. I tried restarting apache server as well. But not working . -
Render dynamic Django form fields
I am creating forms with dynamic fields (and field names) using the below code class BuyItemForm (forms.Form): def __init__(self, inventory_list, *args, **kwargs): super(BuyItemForm, self).__init__(*args, **kwargs) for item in inventory_list: self.fields["count%s"%item.item_name] = forms.IntegerField() self.fields["price%s"%item.item_name] = forms.FloatField() So I get a form that has field names like "counteggs", "priceeggs", "countmilk", etc... when these items are in the inventory_list I now want to render the fields manually in my template. I am able to iterate through the set of fields, for example {% for field in form %} {{ field }} {% endfor %} But I am unable to pick out each field individually by using the field name in a string. I have tried {{ form.fields['counteggs'] }} but this doesnt work. Any ideas how I can make this work? -
django-selenium TypeError: 'str' object is not callable
Doing a simple test of a clicking dropdown and seeing if the menu is displayed. dropdown_user.click() expanded = dropdown_user.get_attribute("aria-expanded") self.assertTrue= (expanded) settings = self.browser.find_element_by_id('dropdown-user-settings') self.assertTrue(settings.is_displayed()) Gives me this error when I run the test. I cant figure why settings is a str. self.assertTrue(settings.is_displayed()) TypeError: 'str' object is not callable -
Issue with TASTYPIE_SWAGGER_API_MODULE setting
I am using tastypie swagger for my api documentation. Even though I have defined the TASTYPIE_SWAGGER_API_MODULE in my setting.py file its still showing the error Must define TASTYPIE_SWAGGER_API_MODULE in settings as path to a tastypie.api.Api instance what is the issue? -
Django form doesn't validate,
Django form doesn't validate, have no idea why. Originally I supposed it was because I added one more hidden input filed to the form(is is actually allowed? found nothing related in docs ) but I deleted it and nothing changed. the form: class TicketForm(forms.ModelForm): class Meta: model = Ticket fields = ('upload','ownership','price','comment','ticket_type') widgets = { 'upload': forms.FileInput( attrs={'id': 'fileinput', 'required': True, 'name':'pdf', 'placeholder': 'Say something...'} ), } model: class Ticket(models.Model): upload = models.FileField(upload_to='media/tickets/') ownership = models.ForeignKey(UserProfile) event = models.ForeignKey(Event) comment = models.CharField(max_length=2000) approved = models.BooleanField(default=False) sold = models.BooleanField(default=False) price = models.IntegerField(blank=False, default=0) TICKET_CHOICES = ( ('DG', 'Digital'), ('RL', 'Real'), ) ticket_type = models.CharField( max_length=2, choices=TICKET_CHOICES, default='Digital', ) in template: <form method='POST' action="/upload_ticket/" class="pdf_form"> {% csrf_token %} {{ form.as_p }} <!-- <input type="hidden" id="pk_input" value="{{ selected.id}}" name="event_id"></input> --> <input type="submit" id='submit_hidden'>Save</input> </form> In views if I remove if form.is_valid() the error is obvious The Ticket could not be created because the data didn't validate. The file to be loaded is pdf file. Do you have any ideas why it doesn't validate? -
How to access pk in views (Django)
I'm writing a small chat programm in Django but have problems getting any further. Here's the code: models.py from django.db import models from datetime import datetime from django.utils import timezone class Chat(models.Model): chatname = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.chatname class Comment(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) commenter = models.CharField(max_length=30) comment = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.comment urls.py from django.conf.urls import url from . import views from django.views.generic import ListView from chat.views import CommentList app_name = 'chats' urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^comments/(?P<pk>[0-9]+)/$', views.CommentList.as_view(), name='comments'), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import authenticate, login from django.views import generic from .models import Chat, Comment def index(request): username = None if request.user.is_authenticated(): username = request.user.username chats = Chat.objects.all()[:10] context = { 'chats':chats } return render(request, 'chat/index.html', context) class CommentList(generic.ListView): queryset = Comment.objects.filter(chat_id=1) context_object_name = 'comments' My comment_list.html {% extends "chat/base.html" %} {% block content %} <a href="/chat/">Go back</a> <h3>Comments</h3> <h2>{{chat.id}}</h2> <ul> {% for comment in comments %} <li>{{ comment.commenter }}: {{ comment.comment }}</li> {% endfor %} </ul> {% endblock %} My database structure contains these two models: Chat and Comment. Each chat(room) is supposed to … -
Haystack skipping my class but it's in search_indexes.py
I'm trying to work through the first steps with haystack and elasticsearch in django, and it looks like everything is set up right - no errors and I put everything where it says to - but it still skips my class... Here is my search_indexes.py: import datetime from haystack import indexes from common.models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) type = indexes.CharField(model_attr='type') category = indexes.CharField(model_attr='category') def get_model(self): return Product def index_queryset(self, using=None): # Used when the entire index for model is updated. return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now()) Here's my template search.html (which I can access without issue): {% extends 'base.html' %} {% block content %} <h2>Product search</h2> <form method="get" action="" class="form" role="form"> {{ form.non_field_errors }} <div class="form-group"> {{ form.as_p }} </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Search"> </div> {% if query %} <h3>Results</h3> <div> <table class="table table-striped table-bordered" cellspacing="0" id='result_table'> <thead> <tr> <th>name</th> <th>category</th> </thead> <tbody> {% for result in page.object_list %} <tr> <td>{{ result.type }}</td> <td>{{ result.category }}</td> </tr> {% empty %} <tr>No results found.</tr> {% endfor %} </tbody> <table> </div> {% endif %} </form> {% endblock content %} {% block extrajs %} <script> $(document).ready(function() { $('#result_table').DataTable({ "searching": false }); } ); </script> {% endblock %} And when … -
Is it necessary to have all the types of requests in an app even though only post is being used for that app?
I have an app in django project which is exposed to only post method. I want to know whether it is compulsory to expose this app to other types of requests like get, put, and delete or not. Thank you in advance -
Segmentation fault with Django tests
When I run tests it will throw [1] 26433 segmentation fault ./manage.py test -v 3 Causing code: def test_order_create_from_bundle_no_trainee(self): # setup Something.objects.create(owner=self.user, name='test') If I run ONLY THIS TEST it will be fine, but if I run all tests it keeps crashing. Here is the weird part: If that code is in any other test case (which it is), all will work fine. What could cause this, and how could I debug what crashed? Using Django 1.10.1, python 2.7, sqlite3 on OSX 10.11.6. -
No model tables are created for a Django migration
I have searched other articles (like this one) for a solution, but nothing has helped so far... I realized while working on my project that I needed to alter the model, changing a primary key to an AutoField rather than use a custom field. I knew this would cause a lot of issues since I have quite a few ForeignKey fields, so I wanted to drop all of my tables, clear out the migrations, and just let the migrations re-generate all of the the tables. The problem is that even though I dropped all of the tables (and eventually the whole database, due to the django_migrations table and any other latent data), cleared out all of the project/app/migrations directories, when I run manage.py makemigrations/manage.py migrate, it only creates the built-in tables (the auth_* and django_* tables) and none of my model tables get recreated. Where else do I need to clean up in order to be able to start over with a fresh database model? I thought that clearing out the migrations directories would be sufficient, but there's something else I'm missing. Thanks. -
How to return html content without escaping in serializer?
I have model with TextField that contains html. Let's say I have row that contains <a href="http://googke.ru">google</a> in TextField. The API returns "<a href=\"http://googke.ru\">google</a>". How can I remove " escaping? -
How to return users posts within the same layout in template? Django
On the summary page I'm displaying all of the users favourite posts: aircraft and airline. I've got the fav posts working for the aircraft, but since the aircraft model is so similar to the airline one, I don't want to create a second section for the airline posts. I want to posts to be merged in the same section. The airline model only has different fields like: fleet size, no. of destinatons, alliance. They way I've styled both of them is the same. How do I merge them? I know you use an if statement but Im confused on how to do it? View def account_overview(request): fav_aircraft = FavoritedAircraft.objects.filter(user__id=request.user.id) fav_airline = FavoritedAirline.objects.filter(user__id=request.user.id) return render(request, 'account/account_overview.html', {'favAircraft':fav_aircraft,'favAirline':fav_airline}) Template {% if favorite %} {% for favorite in favAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><img src="{{ favorite.aircraft.image.url }}" width="200px" height="200px" alt="{{ favorite.aircraft.title }}"/></a> <h3 class="name"><a href="{{ favorite.get_absolute_url }}">{{ favorite.aircraft.name }}</a></h3> <h4>Manufacturer: <i>{{ favorite.aircraft.manufacturer }}</i></h4> <h4>Range: <i>{{ favorite.aircraft.maximum_range }} NM</i></h4> <h4> Passengers: <i>{{ favorite.aircraft.passengers }}</i></h4> <h4> Speed: <i>{{ favorite.aircraft.cruising_speed }} KT</i></h4> <button class=" favorite btn btn-default {% if aircraft.id in favorited_aircraft_ids %}added{% endif %}" data-aircraft-id="{{ aircraft.id }}"><span class="add">Add</span><span class="remove">Remove</span> Favorite</button> </div> </div> {%endfor%} {% else %} <h2 class="text-center">Opps.. You don't seem to … -
Filtered Django Admin TabularInline - Default value ignored when creating
I have the following models: class ReportingSettingRule(models.Model): settings = models.ForeignKey('ReportingSettings', related_name='+', null = True) filter_type = EnumField(choices=['type1', 'type2'], null = True) filter_field = EnumField(choices=['field1', 'field2']) filter_rule = EnumField(choices=['contains', 'equal', 'not_equal', 'not_contains']) filter_value = models.CharField(max_length=250) class ReportingSettings(models.Model): dashboard = models.OneToOneField('Dashboard', related_name='reporting_settings') I want to let the admin to modify (add/update/delete) in 2 tabular inlines according to the filter_field. Currently I have 2 inlines in which I override the get_queryset so it filters only the relevant items: class ReportingSettingsRuleType1(TabularInline): def get_queryset(self, request): qs = super(ReportingSettingsRuleType1, self).get_queryset(request) qs = qs.filter(filter_type='type1') return qs class ReportingSettingsRuleType2(TabularInline): def get_queryset(self, request): qs = super(ReportingSettingsRuleType2, self).get_queryset(request) qs = qs.filter(filter_type='type2') return qs My problem is that when creating new instance, there is no default value for the filter_type. Any Idea's on how to override the default value for the column I filter by? -
View list of only current user objects, Django REST
I have 2 views: /notes/ and /notes// In note model in models.py I have owner variable, that stores owner's login. Because I want to have many users, I don't want them to see other's notes, so I created the permission: class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.owner == request.user I set this permission to NotesList(generics.ListCreateAPIView) and NotesDetail(generics.RetrieveUpdateDestroyAPIView). Now user can't view other's notes if he will go to /notes/<pk>/, but in /notes/ he can view the full list anyway. So, how can I change it? I want to see in notes list only my notes. I think the right way is to filter queryset = Snippet.objects.all().filter(owner=...) but can't think right away.