Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python 2.7 or 3 for Django development now(2016)?
i read answers answered 2013 or something. I just want to know about now. Which is better 2.7 or 3.x for Django -
send request body using a decorator in python
I have a function in a django project something like this: class my_class(): def post(self, request, id, format=None): logger.info( ''.join( ["id"+str(request.get('id')), "name"+str(request.get('name')), "grade"+str(request.get('grade'))] ) ) row = Student( id = request.get('id'), name = request.get('name'), grade = request.get('grade') ) row.save() Now I want to have a decorator(@logger) around my this function which logs everything inside (logger.info). i.e I should only add @logger above the function definition and can log all the request body. Can someone help me how can I do this. I am facing problem in sending the request body from post to the decorator. -
django python social auth get facebook profile picture
I'm using Django and I'm trying to create a profile page which shows the user's facebook profile picture. I am using Python Social Auth package, and also managed to log in via Facebook. Now the problem is I'm not able to show the Profile Picture. Through my Django admin panel, I'm able to see the user's facebook Uid and data, but I can't seem to be able to access them through the template {{ user.uid }} (something like that). I'm not sure how I can do it and I have been googling all day and people seem to be talking about the pipeline. I don't understand the docs exactly and it has been really confusing. Everyone seems to talk about using pipeline and adding it into the settings and then they just stop after that. But I'm trying to get it to show on the template. I hope you guys could give some assistance. Thank you. -
Cant load css of Glyphicon. bootstrap - django
I work in Django, and trying to load the css file of the Glyphicon for i can use that icons. I download the css file named "bootstrap.css" from bootstrap, and then upload this file to my statics files on the "css" directory. The staticfile loading its not the problem, becaues another css files i put in "css directory" are work. Should i do more actions instead of just upload "bootstrap.css" to my static files? i saw there (in the downliaded zip file) a "map" file for that css file, but i didnt think it connected. -
Django ORM join without foreign keys and without raw queries
A class AKeywords(models.Model): id = models.AutoField(primary_key=True, db_column="kw_id") word = models.CharField(max_length=200) ... class Meta: managed = False db_table = '"A"."Keywords"' B class BKeywords(models.Model): id = models.AutoField(primary_key=True, db_column="kw_id") word = models.CharField(max_length=200) ... class Meta: managed = False db_table = '"B"."Keywords"' I have another model where i would like to perform my join. class XKeywords(models.Model): ... k_id = models.IntegerField(blank=True, null=True) ... class Meta: managed = False db_table = '"public"."XKeywords"' I have two models that are very similar, one comes from a database schema and another from another database schema. A third model that will be to join with table A or B has i want. How can i join model A or B without using foreignkeys and raw queries? -
When and how to validate data with Django REST Framework
I have a model which is exposed as a resource with Django REST Framework. I need to manually create the objects when a POST requests is performed on the related endpoints, that why I use a generics.ListCreateAPIView and override the create() method. However I need to check that the parameters given in the payload of the POST request are well-formed/existing/etc... Where shall I perform this validation, and how is it related with the Serializer? I tried to write a validate() method in the related Serializer, but it is never called on POST requests. class ProductOrderList(generics.ListCreateAPIView): model = ProductOrder serializer_class = ProductOrderSerializer queryset = ProductOrder.objects.all() def create(self, request, *args, **kwargs): data = request.data # Some code here to prepare the manual creation of a 'ProductOrder' from the data # I would like the validation happens here (or even before) po = ProductOrder.objects.create(...) class ProductOrderSerializer(serializers.ModelSerializer): class Meta: model = ProductOrder def validate(self, data): # Never called # Is it the good place to write the validator ?? -
Django: Not Found static/admin/css
I just deployed my first Django app on Heroku but I notice that it doesn't have any CSS like when I runserver on the local machine. I know there's something wrong with static files but I don't understand much about it even when I already read the docs. I can do python3 manage.py collectstatic to create a static folder but I don't know where to put it and how to change the DIRS in settings.py. I really need some help to get rid of it. settings.py: DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'household_management', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_ROOT = 'static' STATIC_URL = '/static/' heroku logs: 2016-09-02T10:42:09.461124+00:00 heroku[router]: at=info method=GET path="/" host=peaceful-earth-63194.herokuapp.com request_id=33fc071d-344c-47e7-8721-919ba6d5df65 fwd="14.191.217.103" dyno=web.1 connect=2ms service=53ms status=302 bytes=400 2016-09-02T10:42:09.760323+00:00 heroku[router]: at=info method=GET path="/admin/login/?next=/" host=peaceful-earth-63194.herokuapp.com request_id=c050edcd-02d9-4c39-88ba-8a16be692843 fwd="14.191.217.103" dyno=web.1 connect=1ms service=45ms status=200 bytes=2184 2016-09-02T10:42:10.037370+00:00 heroku[router]: at=info method=GET path="/static/admin/css/login.css" host=peaceful-earth-63194.herokuapp.com request_id=ec43016a-09b7-499f-a84b-b8024577b717 fwd="14.191.217.103" dyno=web.1 connect=2ms service=9ms status=404 bytes=4569 2016-09-02T10:42:10.047224+00:00 heroku[router]: at=info method=GET path="/static/admin/css/base.css" host=peaceful-earth-63194.herokuapp.com request_id=6570ee02-3b78-44f4-9ab9-0e80b706ea40 fwd="14.191.217.103" dyno=web.1 connect=1ms service=16ms status=404 bytes=4566 2016-09-02T10:42:10.030726+00:00 app[web.1]: Not Found: /static/admin/css/login.css 2016-09-02T10:42:10.043743+00:00 app[web.1]: Not Found: /static/admin/css/base.css 2016-09-02T10:48:56.593180+00:00 heroku[api]: Deploy d1d39dc by huyvohcmc@gmail.com 2016-09-02T10:48:56.593290+00:00 … -
Nodejs on Windows server?
I am an entry web developer enjoying using nodejs and angulajs. Recently, our company got a new project and we are required to build an web app that communicate with a software and a database. The problem is a server we going to use is Windows server. I think we are open to use any other frameworks, such as django, nodejs, or rails. But we are very strict to use only Windows (I don't really why.) My question is "Is nodejs still working good with Windows server?" If it doesn't, I prefer to us Python or any other frameworks (except php, I am not so much interested in php). I am looking forward to hearing your any opinions! Thanks -
Python : 'tuple' object has no attribute 'values'
Traceback: File "/Users/smartSense/Pinank/Django/Work/MadhaparDemo/MadhaparDemo/snippets/vi ews.py" in snippet_list 21. return JSONResponse(serializer.data) Exception Type: AttributeError at /snippets/snippets/ Exception Value: 'tuple' object has no attribute 'values' When i'm calling my applications class url its giving me the above error, My Views.py is as follow, class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def snippet_list(request): if request.method == 'GET': snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400) @csrf_exempt def snippet_detail(request, pk): try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = SnippetSerializer(snippet) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() return HttpResponse(status=204) I have a hard time figuring out why this error occurs. How can i find out where that tuple is in my code? -
I can use ajax from /edit but not from /detail
Django 1.10. From DetailView I want to update the model object via ajax. Well, the model object is updated. But the ajax success function can't get data from the post method. I occur in failure function. In other words, in Django in UpdateView I can stop at a breakpoint in form_valid, control that it returns an HttpResponse with code 200. And later if I refresh page with detail information, I can see that the model object has changed. But in In Chrome dev tools while debugging js I occur in fail function. And jqXHR.status=0, textStatus = "error", errorThrown="". I have prepared a simulation of my real situation: https://Kifsif@bitbucket.org/Kifsif/ajax_update.git There is a difference: this UpdateView renders the general_detail.html. In real life it should render partial_detail.html. Well, it is ajax, we don't need to reload the whole page. So, this simulation renders the whole page. What does it mean? It means that: 1) If I'm in http://localhost:8000/1/detail, pressing AjaxEdit link leads me to the failure. Not working. In Chrome developers tools I occur in failure function. 2) I return to http://localhost:8000/1/detail, press Edit. I occur in http://localhost:8000/1/edit. This is ordinary editing without ajax. But the view is organized so that to render … -
Notification to user from admin
I am new in Django and don`t know the best way to realise next functionality in my project. In my django project I have users with different roles. One of them is admin who can create project. I mean that I have model with fields (project_name, project_managers) which filled by admin. The managers of the project are users of the system, admin can choice some of them. After all how to show them notification in real time that they was managers of the current project. Is it makes by websockets or Jquery or something else. I need some ideas how to realise that with detail explanation if it possible. -
Use model from the versioned app registry globally
I'd like to run a custom command in my migration, that calls functions from other modules. These functions use some models, and as expected I ran into schema version mismatch (OperationalError: (1054, "Unknown column 'foo' in 'bar'"). If I were to use those models in the custom command I'd access the model with apps.get_model('my_app', 'bar'), but as those models are used in the external functions, I can't do that. I'm sure, someone ran into this before although I couldn't find anything. I was thinking about using the unittest.mock.patch decorator but it doesn't feel like the right solution. I'm wondering if there's a more general solution for this? -
django transaction doesn't works
i'm using django(1.10) and django-restframework(3.4.6). i'm trying to adapt transaction on my code, but it not works! code is below: class Home(View): def get(self, request): with transaction.atomic(): Episode.objects.filter(id=1).update(volume=12) if True: raise Exception('test exception') Episode.objects.filter(id=2).update(volume=13) return render(request, 'home/home.html') i already tried with decorator (@transaction.atomic), but it doesn't works too! and i tried with ATOMIC_REQUESTS = True in setting, but but it doesn't works too... i can't understand why this code not works... what am i missing? db setting here: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dragon', 'USER': ..., 'PASSWORD': ..., 'HOST': ..., 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'STRICT_TRANS_TABLES', } ... mysql db engine is InnoDB. mysql tx_isolation: REPEATABLE-READ -
Django crisppy-forms warnings when excluding a field from a form
In my project each user can have multiple enemies, like this: models class EnemyModel(models.Model): name = models.CharField(max_length=128) weapon = models.CharField(max_length=128) related_user = models.ForeignKey(UserProfile) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Only user can add enemies to his profile, so I made a form like this: forms class AddEnemyForm(forms.ModelForm): class Meta: model = EnemyModel exclude = ['related_user'] # only current user Unfortunately cirpsy-forms module have a problem with rendering this form: console WARNING:root:Could not resolve form field 'related_user'. Traceback (most recent call last): File "/home/sch/myenv/local/lib/python2.7/site-packages/crispy_forms/utils.py", line 92, in render_field field_instance = form.fields[field] KeyError: u'related_user' How to get rid of this warning? -
Value of settings.DEBUG changing between settings and url in Django Test
I'm trying to set up test for some URLS that are set only if we're in debug. They are not set because apparently the value of DEBUG change between my setting file and url.py. I've never encountered this problem before, and I don't remember doing anything particularly fancy involving DEBUG value. Here's my urls.py : print "settings.DEBUG in url: {}".format(settings.DEBUG) if settings.DEBUG: urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"... Here's my setting file : DEBUG=True print "DEBUG at the end of the settings: {}".format(DEBUG) The content that fail in my test : reverse("debug_not_found_page"), Here's the output of the test : DEBUG at the end of the settings: True settings.DEBUG in url: False Creating test database for alias 'default'... .E (...) NoReverseMatch: Reverse for 'debug_not_found_page' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] The reverse is working if I add "settings.DEBUG=True" at the beggining of my url.py file. Any ideas when and why my value for DEBUG is changing between settings and urls ? -
Django: Strange HTTP Status codes for non-existing URLS
I have a Django website with activated translations (django.middleware.locale.LocaleMiddleware), I someone requests a non-existing page: https://example.com/nonexisting Django then responds with: HTTP/1.1 302 FOUND Date: Fri, 02 Sep 2016 09:15:45 GMT Server: Apache/2.4.7 (Ubuntu) Vary: Cookie,Host Location: https://example.com/de/nonexisting Content-Type: text/html; charset=utf-8 HTTP/1.1 301 MOVED PERMANENTLY Date: Fri, 02 Sep 2016 09:15:45 GMT Server: Apache/2.4.7 (Ubuntu) Vary: Cookie,Host X-Frame-Options: SAMEORIGIN Content-Language: de Set-Cookie: django_language=de; expires=Sat, 02-Sep-2017 09:15:45 GMT; Max-Age=31536000; Path=/ Location: https://example.com/de/nonexisting/ Content-Type: text/html; charset=utf-8 HTTP/1.1 404 NOT FOUND Date: Fri, 02 Sep 2016 09:15:45 GMT Server: Apache/2.4.7 (Ubuntu) Vary: Cookie,Host X-Frame-Options: SAMEORIGIN Content-Language: de Set-Cookie: django_language=de; expires=Sat, 02-Sep-2017 09:15:45 GMT; Max-Age=31536000; Path=/ Content-Type: text/html; charset=utf-8 The user receives in this order: 302,301,404 How can I achieve that the user directly gets the 404? -
SEO: Does it hurt to have a language detection before 404
I have a Django website with activated translation middleware for several languages. If a user try to open example.com/abc this happens: 1) the middleware detects the user langauge (from cookie, from browser, then fallback) and redirect to i.e. example.com/en/abc 2) the middleware detects that this page does not exist and sends a 404 For these non-existing pages I have first a 301 and then a 404. Does this redirect hurt my SEO ranking? -
Do not show certain fields in admin page
In Django, you get the model editor for free in the admin/ pages. This all works fine, but I have a few fields in my models that are generated and should never be touched by anybody through a form. How can I exclude them from these admin/.../change/ forms? I added exclude to the ModelAdmin: class exampleAdmin(admin.ModelAdmin): exclude = ('field',) class example(models.Model): field = models.CharField(max_length = 100) -
Django watson - custom template for different models
Im trying to have two different search on my site (two different models/apps), but I can't get django-watson to use app template. My app is called mag and is stored in a folder called apps so settings looks like this: INSTALLED_APPS = [ ... 'watson', 'apps.mag', ... ] models.py class Entry(models.Model): title = models.CharField(max_length=255, verbose_name='Tittel') class Meta: app_label = 'mag' apps.py from django.apps import AppConfig from watson import search as watson class MagConfig(AppConfig): name = 'apps.mag' def ready(self): Entry = self.get_model("Entry") watson.register(Entry) views.py class SearchView(ListView): template_name='mag/search.html' context_object_name = 'search_entry_list' def get_queryset(self): if ('q' in self.request.GET) and self.request.GET['q'].strip(): return watson.search(self.request.GET.get('q'), models=(Entry,)) else: return None def get_context_data(self, **kwargs): context = super(SearchView, self).get_context_data(**kwargs) context['query'] = self.request.GET.get('q') return context search.html {% load watson %} {% search_results search_entry_list %} Watson templatetag: @register.simple_tag(takes_context=True) def search_result_item(context, search_result): obj = search_result.object content_type = ContentType.objects.get_for_id(search_result.content_type_id) params = { "app_label": content_type.app_label, "model_name": content_type.model, } # Render the template. context.push() try: context.update({ "obj": obj, "result": search_result, "query": context["query"], }) return template.loader.render_to_string(( "watson/includes/search_result_{app_label}_{model_name}.html".format(**params), "watson/includes/search_result_{app_label}.html".format(**params), "watson/includes/search_result_item.html", ), context) finally: context.pop() I have tried to name my template watson/includes/search_result_mag.html and watson/includes/search_result_mag_entry.html, but it still uses my local watson/includes/search_result.html (I have tried to change my local search_result.html and it is beeing rendered from my local … -
Is it an anti-pattern to send a request object to a model method in Django?
I am currently trying to use the fat model, thin view pattern, moving almost all the logic to model methods. While doing it, I am constantly finding myself sending a request object from a view to a model method: model_method(request) and using it in the following way: def model_method(self, request): user_id = request.user.id user_type = request.user.__class__.__name__ ... Is this a good idea? or should I send what I want from the request object to the method, instead of the whole object, like this: user_id = request.user.id user_type = request.user.__class__.__name__ model_method(user_id, user_type) What is the correct way? -
Django Rest Framework debug post and put requests
I use DRF extension to se json list for model, and there i can debug with debug-toolbar that GET request, but how can i debug POST and PUT requests? I have this for settings in debug mode: INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) DEBUG_TOOLBAR_PATCH_SETTINGS = False INTERNAL_IPS = ( '127.0.0.1' ) Now, when i try with Intercept redirects in debug-toolbar, it doesn't show me toolbar when i do POST. -
Python Django REST call returning object number instead of object name
I'm new to Python, and I guess I'm serializing it incorrectly. This is the REST call result: authors/models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): auto_increment_id = models.AutoField(primary_key=True) name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=False, null=False, related_name='book_author') contents = models.TextField('Contents', blank=False, null=False) def __str__(self): return self.name authors/views.py from authors.models import Book, Author from authors.serializers import BookSerializer, AuthorSerializer from django.shortcuts import render from rest_framework import generics class ListCreateBooks(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer class ListCreateAuthor(generics.ListCreateAPIView): queryset = Author.objects.all() serializer_class = AuthorSerializer authors/serializers.py from authors.models import Book, Author from rest_framework import serializers class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('name', 'author') class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author book_author = 'name' I'm new to Django, but I tried many things, in my views.py I've added another class called AuthorSerializer importing from a corresponding class I created in serializers, but then I realized that I have no clue how to add my ListCreateAuthor to: url(r'^api-auth/', ListCreateBooks.as_view(), name='list_books') I've added another parameter with ListCreateAuthor.as_view() that gave me an immediate error (and which also didn't make much sense) Am I going the wrong … -
Model design for restaurant, meal and meal category
I am planning to develop a food delivery app from local restaurants. I am thinking for the best design. I have designed a json too for modeling API.However i am confuse with menu part. Should meal be in the restaurant as a foreign key or restaurant be a foreignkey in the meal. Simple concept of my app is A restaurant prepares various meals to serve various kind of customer. A meal is associated with category like a meal can be veg, non-veg. Customer(User) might order drinks too. Is my model design and api design apt for such kind of scenario? class Restaurant(models.Model): name = models.CharField() slug = models.SlugField() owner = models.ForeignKey(User) location = models.CharField() city = models.CharField() features = models.ManyToManyField(FeatureChoice) # dinner, launch, nightlife, timing = models.ManyToManyField(TimingChoice) # sunday, monday, tuesday, is_delivery = models.BooleanField(default=True) # meal = models.ForeignKey(Meal) main confusion is here class Meal(models.Model): restaurant = models.ForeignKey(User) name = models.CharField() price = models.FloatField() quantity = models.PositiveIntegerField() image = models.ImageField() rating = models.IntegerField() class MealCategory(models.Model) meal = models.ForeignKey(Meal) name = models.CharField() slug = models.SlugField() json design for REST API [ { 'name':'Kathmandu Fast Food', 'owner':'Sanskar Shrestha', 'location':'Koteshwor', 'city':'Kathmandu', 'features':[ { 'features':'Breakfast' }, { 'features':'Launch' }, { 'features':'NightLife' }, ], 'timings':[ { … -
GeoDjango distance query with srid 4326 returns 'SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system.'
I'm trying to fetch nearby kitchens, within 4 km radius from a given lat/long. My spatial backend is spatialite and settings are, INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'rest_framework', 'oauth2_provider', 'kitchen', ) DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Here is my model from django.contrib.gis.db import models from django.contrib.gis.geos import Point class Kitchen(models.Model): id = models.CharField(max_length=100,primary_key=True) #id = models.AutoField(primary_key=True) name = models.CharField(max_length=100,blank=False) address = models.CharField(max_length=1000, blank=True, default='') contact_no = models.CharField(max_length=100,blank=True, default='') location = models.PointField(srid=4326, geography=True, blank=True, null=True) objects = models.GeoManager() My query from Django shell is, from kitchen.models import Kitchen from django.contrib.gis import measure from django.contrib.gis import geos current_point = geos.fromstr('POINT(%s %s)' % (76.7698996, 17.338993), srid=4326) Kitchen.objects.filter(location__distanc e_lte=(current_point, measure.D(km=4))) which return the below Value Error, SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system. Distance objects; use a numeric value of your distance in degrees instead. Setting a different projected srid in the model(ex. 3857, 24381 etc) returns incorrect results. Some help here would be greatly appreciated. -
How to create a datetime aware for DJango in UTC
I have configured my timezone in settings, as America/Guatemala and I have some datetime fields in my models, I'm using default=timezone.now but it is not saving my local hour, which is UTC-6:00, is saving it as UTC-00:00. I can't change that because now there is some important data stored in the database in that way. I have problems retrieving the data in a queryset, I send a string in request.POST like this: date='1/09/2016' And I have tried this to configure my date for the query: f=date.split('/') if len(f)>1: initialdate=datetime.datetime(int(f[2]),int(f[1]),int(f[0]),0,0,0,tzinfo=pytz.UTC) finaldate=datetime.datetime(int(f[2]),int(f[1]),int(f[0]),23,59,59,tzinfo=pytz.UTC) And this is my queryset: sale=Sale.objects.filter(Q(pk=int(cod))|Q(sale_date__range=(initialdate,finaldate))) But because of the 6 hours of difference between my saved data and my local date and time, if I store a Sale at 6:01pm of my local time, the saved data is stored as 00:01am of tomorrow. If i want to check all the sales that I made today, it doesn't show me the sales after 6pm, because they are saved in a different date. I have another querys where I send two differents dates, and I use the same code, I just add time 0,0,0 to the first date, and 23,59,59 to the second date, but I have the same problem. My …