Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tastypie login returns HttpResonse 500
I'm trying to get a Tastypie login system to work, however when I send a json request with the user data, the server responds with Http 500. I have looked through all of my code and tried to debug the issue but nothing I try is working. I've looked around and can't find anything to help me. Does anyone know how I can go about fixing this issue or if there is something I should be doing that I am not. Thanks. api.py class UserResource(ModelResource): raw_password = fields.CharField(attribute=None, readonly=True, null=True, blank=True) class Meta: queryset = User.objects.all() fields = ['first_name', 'last_name', 'email'] allowed_methods = ['get', 'post' ] resource_name = 'user' def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/login%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view("login"), name="api_login"), url(r'^(?P<resource_name>%s)/logout%s$' % (self._meta.resource_name, trailing_slash()), self.wrap_view("logout"), name="api_logout"), ] def login(self, request, **kwargs): self.method_check(request, allowed=['post']) data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json')) username = data.get('username', '') password = daya.get('password', '') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return self.create_response(request, { 'success': True }) else: return self.create_response(request, { 'success': False, 'reason': 'disabled', }, HttpUnauthorized) else: return self.create_response(request, { 'success': False, 'reason': 'incorrect', }, HttpUnauthorized) def logout(self, request, **kwargs): self.method_check(request, allowed=['get']) if request.user and request.user.authenticated(): logout(request) return self.request.create_response(request, {'success': True}) else: return self.request.create_response(request, … -
Group By Django ORM
I want to do a simple group by with django ORM. SELECT * FROM user AS u JOIN user_photo AS up WHERE u.`user_id` = up.`user_id` GROUP BY up.`user_id`; Structure user_photo: id | photo | user_id Structure user: id | name | status | description | paid | user_id I have another table with user photos that users upload to the database. I can pull the informations from the user but I want only one and the last photo that the user uploaded from the user photo table. Anyone can help? -
Django, JSONField, Postgres, and F() object comparison
I am hoping to make a Django query by comparing two values within a JSONField class. I ran across Django F() Objects for references fields on the model, but it doesn't appear to work with JSONField as it tries to do a JOIN with the later section. So, for example: class Event(models.Model): data = JSONField(default=None) Let's assume the data field looks something like this: { "value_1":20, "value_2":25 } I was hoping to query it like such: events = Event.objects.filter(data__value_2__gte=F('data__value_1')) However, the error is something like this: Cannot resolve keyword 'value_1' into field. Join on 'data' not permitted. Any idea how to filter based on a comparison of value_1 and value_2? -
When debugging Javascript, consoles on my browsers still show errors after fix
As I'm trying to debug angular errors on the console, I fix old errors but the error will still show in the console. for example, I fixed a misspell error, but the console shows that the error still remains only until I refresh the browser's cache can i progress in debugging. Problem happens in both firefox and chrome. it is a django application, so im running test server off python -
Django show Field Based on ChoiceField Selection
I've been having difficulty finding out how to create a text field in django that is dependent on the selection of another field in the form. It is only desired to show this field when the selection is set to, in this case "Purchase". Right now I'm running into an issue where it is not updating based on the drop down selection, but only after I hit a button to "submit" the form. Is there some way to acquire the current selected value, or to manually trigger the clean/submit functionality? {% if field != form.purchase_order %} {{ field.label_tag }} {{ field }} {% endif %} {% if field == form.purchase_order and form.purpose.data == 'PURCHASE' %} {{ field.label_tag }} {{ field }} {% endif %} -
Django - get query works, filter and all result in error
I'm trying to query my database for an artist and their works, but I can't seem to figure out what I'm doing wrong as I'll explain below. #models.py class Artist(models.Model): name = models.CharField(max_length=100) artist = models.CharField(max_length=150) created_by = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class ArtistPieces(models.Model): artist = models.ForeignKey(Artist, on_delete = models.CASCADE) piece_name = models.CharField(max_length=50) details = models.CharField(max_length=100) #views.py from .models import Artist, ArtistPieces class EditArtistViewSet(viewsets.ViewSet): def edit(self,request,artist_id): artist = Artist.objects.select_related().get(pk=artist_id) data = model_to_dict(artist) return render(request, 'ArtistInfo/edit.html', {'editing': 'true', 'edit_data' : json.dumps(data) } ) def submit_edit(self,request): return render(request, 'ArtistInfo/edit.html') The above works, but it doesn't select any of the data from the ArtistPieces model, despite the primary key. Then after reading this post about using select_related I realized that rather than looking up the artist, I'd have to look up ArtistPieces by the foreign_key, and use select_related to find the info about the artist. I then tried this def edit(self, request, artist_id): artist = ArtistPieces.objects.get() data = model_to_dict(artist) Which resulted in the following error get() returned more than one ArtistPieces -- it returned 5!. Searching, I found this post which states that I need to use filter rather than get. I then tried this def edit(self, request, artist_id): artist … -
Vanilla example of submitting a stripe payment form for processing in django?
I'm working to get a single charge processed using stripe and django. There are a lot of packages to help with this such as pinax-stripe but all of those are centered on storing a customers information in a db and then charging regularly based on a subscription. I am just hoping someone can demonstrate through axiom and example the simplest way to submit a form to stripe for tokenizing and then to submit to the django server to process. -
Django: Conceptual Design of "Object Stream" with Filters
I need some help designing an implementation for a segment of a website that I'm building using django. One of my django models is a "Clothes Item". Each clothes item has fields like (gender, color, price, size, type, etc). On the home page of my website, I want to have a clothes stream, which will initially display all clothes items in the database. There will also be buttons/input fields at the top where the user can apply multiple filters (each of which will correspond to a field that each clothes item has) to the collection of clothes. Every time the user refreshes or navigates away and then later returns, I want all of the filters to be unapplied. I have tried 3-4 different implementations but each time, I get reasonably far along before hitting some critical issue that I can't seem to work around. Other times, I figured that I could work around the issue, but the solution I would have to use is clunky and inefficient. What would be the best way to go about implementing this logic? I don't need specific code (unless the method is particularly tricky or niche), but rather just ideas of how to proceed … -
Django Forms forms.DateInput / forms.DateField: formatting inconsistency between {{ form.datefield }} and {{ form.datefield.value }} in template code
my settings.py: LANGUAGE_CODE = 'de' TIME_ZONE = require_env("TIME_ZONE_IDENTIFIER") USE_I18N = True USE_L10N = True USE_TZ = True DATE_INPUT_FORMATS = [ '%d.%m.%Y', '%d.%m.%y', # European '%Y-%m-%d', # ISO (for native mobile datepickers) '%m/%d/%Y', '%m/%d/%y', # US '%d %b %Y', '%d %B %Y', # some long formats ] DATE_FORMAT = 'j F Y' TIME_FORMAT = 'H:i' DATETIME_FORMAT = 'j F Y H:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j N Y' SHORT_DATETIME_FORMAT = 'j N Y H:i' FIRST_DAY_OF_WEEK = 1 forms.py: class SomeForm(forms.ModelForm): birth_date = forms.DateField( widget=forms.DateInput( format='%Y-%m-%d', attrs={ "class": "form-control text-input", } ), input_formats=settings.DATE_INPUT_FORMATS, initial=datetime.datetime.today, # required=False, # label=_("birth date"), ) now, if I want to construct the input myself in the template I would do: <input name="{{ form.birth_date.name }}" id="{{ form.birth_date.id_for_label }}" class="form-control text-input" type="text" value="{{ form.birth_date.value }}" {% if form.birth_date.field.required %}required{% endif %}/> In the image below you can see the difference between the above template code and {{ form.birth_date }}: {{ form.birth_date }} respects the formatting, {{ form.birth_date.value }} doesnt. Can this be explained somehow or should I add this to the Django bug tracker? -
load js file from app django-cms
Hi everyone I create a app with 3 fields (html, css and js) the apps have to embed this 3 fields in the template of my app like this. I use a placeholder to show this fields. <style type="text/css"> {{instance.css_code|safe}} </style> {{instance.html_code|safe}} <div id="containerChart" style="height: 400px; min-width: 310px"></div> <script type="text/javascript"> {{instance.js_code| safe }} </script> What a best way to do that, for example load the javascript code in the footer (with the rest of the javascript code) and in the header the css code Like for example if my placeholder has element load the field js in the footer..etc It is posible! Thanks in advance. -
Writing a custon widget for Django ImageField
I wrote a small plugin to enable previews of ImageFields in Django, I use some custom CSS, JS and HTML markup using the field name. Recently I was asked to use it in multiple forms, so I want to create a widget to not repeat myself but the documentation isn't clear about how to write custom widgets. I know about the render function and the Media class but don't know how to use it properly. I'm putting the code so you can look up for improves. Thanks. HTML <div id="image-uploader"> <!-- this is the ImageField of Django form, input will be rendered with id="id_image" --> {{ form.image }} <div class="thumbnail" id="featured-thumbnail"> <img id="img_id" width="200" height="200" /> </div> <label for="id_image" class="btn btn-primary id-image m-b-0" style="color:#fff;"><span>Choose a file...</span></label> <button id="button-reset" type="button" class="btn btn-default" onclick="clearImageFile()">Clear</button> </div> SCSS #image-uploader{ #id_image{ display: none; } .id-image{ border-radius:4px; } .blog-featured-image{ text-align: center; margin-bottom: 0; .thumbnail{ margin: auto; display: none; padding: 4px; margin-bottom: 5px; border: 1px solid #ddd; border-radius: 4px; -webkit-transition: all .2s ease-in-out; -o-transition: all .2s ease-in-out; transition: all .2s ease-in-out; width: 200px; height: auto; overflow: hidden; } #button-reset{ display: none; } } } JS function clearImageFile(){ var input = document.getElementById('id_image'); console.log(input.value); if(input.value){ try{ input.value = ''; … -
How to determine what decorators a view has in Django?
I know the relative url (ie. /accounts/) and from that I'd like to determine whether or not the view that handles it is decorated with the login_required decorator. -
Reusing views and templates for sub-classed models
Consider the following classes that specializes a django model class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() class CoffeeShop(Place): serves_coffee = models.BooleanField() serves_crossaints = models.BooleanField() I want to generate CRUDs for both type of objects without to write a view for each. The idea would be to create a parameterized view that takes the type of the model object to be created or edited and to display a generic form_class. I think that this is possible but I'm missing the point. -
Django: return json only for api sub-app
urls.py urlpatterns = patterns( url(r'^subapp1/', include('subapp1.urls', namespace='subapp1')), url(r'^api/', include('api.urls')), ) When GET /api/invalid/url sent, 404 html page returned. It seems that this is not right for REST APIs. How to make invalid urls starting with subapp1/ return 404 html page, and make invalid urls starting with api/ return 404 status code and error message in json? Any comments welcomed. Thanks. -
Django models with varied types of functionality
I have a use case where I want to capture various types of reminders for users (auto-generated by business logic) in a Django application. Across all reminders, the attributes are the same (i.e. owner, creator, creation_time, status, completion_time) and they have the same interface (i.e. render_message(), is_valid()). However, there are many types of reminders which should each have their own implementation details for these common functions. Since the model attributes never change it seems like having a single Django model makes sense but then I question the best way to get from a model instance to the specific implementations of functions like render_message(). I'm currently considering having a ChoiceField on the Reminder model called type which would map to the various reminder type classes and then have a helper function within Reminder that will instantiate the appropriate reminder type class based on self.type and call that for functionality like render_message(). Am I missing a better way? Not sure what this pattern is considered or where to look for similar examples of having a single Django model that's associated to a variety of implementations of the same interface. -
Django not reading all columns from table
This is a strange one. Maybe I missed it but I have search through all Django documentation and SF but could not find an answer for this. I have a table with about 30 columns. The table looks like this... Class Customer (models.Model): customer_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) middle_initial = models.CharField(max_length=2) mail_addr1 = models.CharField(max_length=50) mail_addr2 = models.CharField(max_length=50) mail_city mail_state mail_zip bill_addr1 bill_addr2 ... ... active_yn = models.ForeignKey('status', models.DO_NOTHING) # <-- This one ... ... home mobile The offending field is "active_yn". Django keeps spitting out an error saying that it is now a valid field. Here's the things I am sure of: The table definitely have this field in the correct DB, schema, table, etc It is not the last field on the table. inspectdb for this table is also missing this field. I drop and re-add this column and it is still not showing. The field is a TINYINT(3) - referencing a table Django recognized. I am using MySQL I have been trying to debug this for days now. Any ideas? -
Getting error: "TypeError: view must be a callable or a list/tuple in the case of include()." when running Django Server
Every time I try to run my backend server with Django I get the error "TypeError: view must be a callable or a list/tuple in the case of include()." Here is a full traceback: Unhandled exception in thread started by <function wrapper at 0x10e662578> Traceback (most recent call last): File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/lyndseearmstrong/dev/recipe_organizer/backend/recipe_organizer/urls.py", line 8, in <module> url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). Here is … -
Calendar is not being displayed after the chrome is updated. Nothing is changed in the code
I have recently updated the chrome and in my django application. I have a calendar which is a Java Script file. It`s been working fine since many days and after the recent update of the chrome. The calendar is not being displayed. Error 1 -
How do make a Page in Django CMS require login?
I notice there is a login_required parameter to the Page objects, but there doesn't seem to be any way via the admin to actually set it, and even when I set it via the shell, it doesn't seem to do anything. How does one create a page with Django CMS that requires the user to be logged in to see it? Thanks. -
Django REST Framework - Filter foreign key items for POST, PUT and PATCH
I have a simple ModelSerializer : class OfferSerializer(serializers.ModelSerializer): class Meta: model = Offer fields = ('id', 'accepted', 'comment', 'status', 'item_given', 'item_received') With this model : class Offer(models.Model): accepted = models.BooleanField() status = models.BooleanField() comment = models.CharField(max_length=1000) creation_date = models.DateTimeField("date published", default=timezone.now) item_given = models.ForeignKey("items.Item", related_name='item_given', on_delete=models.CASCADE) item_received = models.ForeignKey("items.Item", related_name='item_received', on_delete=models.CASCADE) def __str__(self): return self.comment And it is used by the following view : class OfferViewSet(viewsets.ModelViewSet): queryset = Offer.objects.all() serializer_class = OfferSerializer The foreign key item_given is another model named Item which has a foreign key on user. In the django rest framework's generated form I can select any Item for the item_given field when creating a new offer. But I'd like to be able to select only items where the foreign key user is equal to request.user. I tried editing the def_queryset in the serializer but without success. How can i achieve this? -
How do I filter and display the contents of my table in my django template according to date
I have a template that displays users data (date, name, address, contact no) in a tabular format. How do I apply a filter button on this template that takes in the users date and modifies the table to show the entries for that particular date. `{% extends "app/layout.html" %} Table.html {% block content %} <h1 style="font-size:300%;">ATTENDANCE TABLE</h1><hr /><br /> <table> <tr> <th>DATE</th> <th>NAME</th> <th>SITE</th> <th>TYPE OF LEAVE</th> <th>REASON</th> <th>ARRIVAL</th> <th>TIME IN</th> <th>TIME OUT</th> </tr> {% for topic in topics %} <tr> <td>{{ topic.date }}</td> <td>{{ topic.name }}</td> <td>{{ topic.site }}</td> <td>{{ topic.leave_type }}</td> <td>{{ topic.reason }}</td> <td>{{ topic.arrival }}</td> <td>{{ topic.intime }}</td> <td>{{ topic.outtime }}</td> </tr> {% endfor %} Once this table is displayed, I would like to have a filter button that accepts the date and modifies the table to show entries for that entered date. Would I have to create a new view or just play around with the .html file? I tried using {{variable|date}} filter to no avail . -
How to make post request of an object with array property in django rest framework
In my api the raw data suggested this structure on making a post request. { "empID": "", "fullname": "", "contactnumber": [] } and in the api list here is some of the example structure: { "empID": "DJS1003", "fullname": "Doe, John Smith", "contactnumber": [ { "contactnumber": "123456789" }, { "contactnumber": "321456879" } ] } Now, my object data when making a post request looks like this: contactnumber : Array[2] 0:"444-1234" 1:"0911-124-7854" fullname:"John Doe" empID:"1001" And i got this error that says: contactnumber:[{non_field_errors: ["Invalid data. Expected a dictionary, but got str."]},…] -
Django Models - Managers; how they are implemented?
I’m trying to understand better how Django works, I checked the code but I still have some doubts about how things works. So, objects is an attribute of class Model. Is objects define as a class attribute or instance attribute (I see the used a function add_class to add it ? objects type/class is Manager Is then objects an attribute of class Model and at the same time an instance of class Manager ? Is all() a method of objects instance and the return is a queryset which is an instance of type/classs QuerySet ? -
django channels integration issue, websocket.receive not listening
Going through various blog post, I am trying to implement django channels for websockets functionality with django I am using django 1.9.1 with these set of dependencies: asgi-redis==0.10.0 channels==0.12.0 daphne==0.11.1 settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "test.routing.channel_routing", }, } routing.py from channels.routing import route from .consumers import websocket_receive channel_routing = [ route("websocket.receive", websocket_receive, path=r"^/chat/"), ] consumers.py def websocket_receive(message): text = message.content.get('text') if text: message.reply_channel.send({"text": "You said: {}".format(text)}) After runserver from browser console i am calling this socket = new WebSocket("ws://" + window.location.host + "/chat/"); socket.onmessage = function(e) { alert(e.data); } socket.onopen = function() { socket.send("hello world"); } On above call, in runserver logs I can see a call for websocket, something like this: "[2016/11/15 19:35:39] WebSocket CONNECT /chat/ [127.0.0.1:55499]", but my consumers.py method(websocket_receive) is never called.. Any idea where I may be going wrong ?? -
How do set JWT to be store in local storage so all parts of my domain can access it?
I'm using a django resting framework for my backend and react for my front end. I've set the front end so when logging in the client receives a JSON token after being fully authenticated. However, my backend - specifically the APIs are not receiving this JSON token. Here is what my url conf looks like: router = SimpleRouter() router.register(r'accounts', accountsviews.UserViewSet, 'list') router.register(r'groups', accountsviews.GroupViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^message/', homeviews.message, name="message"), url(r'^stocks_api/', stocksviews.StockList.as_view()), url(r'^passwordreset/', homeviews.passwordreset.as_view(), name='passwordreset'), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api-token-auth/', obtain_jwt_token), url(r'^api-token-refresh/', refresh_jwt_token), url(r'^api-token-verify/', verify_jwt_token), url(r'^reset/done/$', passwordviews.reset_done, name='password_reset_done'), url(r'^reset/(?P<token>[\w:-]+)/$', passwordviews.reset, name='password_reset_reset'), url(r'^', include(router.urls)), url(r'^', homeviews.home, name='home'), ] urlpatterns = format_suffix_patterns(urlpatterns) I feel like the issues might be because my apis (stocks_api, accounts_api, and groups_api) are not nested inside r'^', homeviews.home. If so, how would I go about making JWT global and not just specific for a url?