Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authentication for APIs(JWT and OAuth)
APIs are built using Django Rest Framework, Front End is Angular2 and a 3rd party android application. I have a set of APIs which I want to secure. APIs are currently serving angular2 using JWT authentication. Angular2 app is on the same domain as that of our APIs i.e., both are being served by the same server with different proxies. Now I want to authorize android app to use my APIs using OAuth2. I am using django-oauth-toolkit for my OAuth2 setup, but it doesnt support use of JWT as its bearer token currently. After implementing OAuth2, APIs are not being served if the request is from the same domain too. What is the way around this? If the request is from same domain, the apis should be served, if the request is cross domain, OAuth authorization should take place. -
Signals VS Celery task
So i have this scenario and quite not sure whether celery is the right tool for the job. I have to track the fifth order placed by a user to give them a coupon. Currently i have implemented a signal on the @receiver(pre_save, sender=Order) def pre_save_stuff(): #this has overhead on db since am excluding customers not in #loyalty progamme.They are many do_coupon_stuff() method. However i have now to exclude a particular group of customers with a query that has overhead slowing the request cycle for this order. Does it make sense to user celery in this scenario? -
Django modelformset_factory with crispy forms for images
I would like to create a list of all existing images belonging to a model in an UpdateView. This is the model included in the modelformset_factory from imagekit.models import ProcessedImageField class GalleryImage(models.Model): image = ProcessedImageField(upload_to="gallery", # Resize to fit ration 4:3 (Most common for phone camera's) processors=[ResizeToFit(800, 600), ], format="JPEG", options={"quality": 60}, blank=True, null=True, verbose_name="Afbeelding") gallery = models.ForeignKey("gallery.Gallery", related_name="images", on_delete=models.CASCADE) I created a form, with a related modelformset_factory from crispy_forms.helper import FormHelper from django.forms.models import modelformset_factory class GalleryImageFormInline(ModelForm): class Meta: model = GalleryImage fields = ["image", ] def __init__(self, *args, **kwargs): super(GalleryImageFormInline, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_tag = False self.helper.disable_csrf = True GalleryImageFormset = modelformset_factory(GalleryImage, fields=("image", ), can_delete=True, ) An UpdateView class GalleryUpdateView(LoginRequiredMixin, UpdateView): model = Gallery form_class = GalleryForm def get_context_data(self, **kwargs): context = super(GalleryUpdateView, self).get_context_data(**kwargs) context["images"] = GalleryImageForm() context["updateview"] = True current_images = GalleryImage.objects.filter(gallery=self.object) context["current_images"] = GalleryImageFormset(queryset=current_images) return context def form_valid(self, form): http_response_redirect = super(GalleryUpdateView, self).form_valid(form) images = self.request.FILES.getlist("file_field") for image in images: gallery_image = GalleryImage(gallery=self.object, image=image) gallery_image.save() current_images = GalleryImageFormset(self.request.POST, self.request.FILES) current_images.save() return http_response_redirect def get_success_url(self, **kwargs): return reverse_lazy('gallery:update', args=(self.object.id,)) And in the template: <form action="" class="uniForm" method="post" enctype="multipart/form-data"> {% csrf_token %} {% crispy form %} <hr/> {% crispy images %} <input type="submit" class="btn btn-primary" value="Opslaan"/> … -
Unifying Django and Django Rest Framework various reporting formats
We want to unify the format of the various exceptions returned by our Django REST framework-driven API. We've made use of the custom exception handler that DRF provides, however there are tons of different formats in which the different exceptions are returned (specifically DRF's own ValidationError exceptions) and we want to ensure they are all returned in a consistent manner. Then there are Django's own field validation exceptions that come in their own format (and are not even handled by DRF's custom validation handler). I'm thinking of going down the route of using some kind schema validation (supported by voluptuous or something like cerberus) where I go through all the schemas and if a match is found, then have some mapping from that format into the desired one. Is this an overkill? Is there a simpler way to accomplish this? -
Django Rest Framework: writable nested serializer
I need to manage a JSON like this: { "name": "drink_type", "description": "A type of drink", "values": [ { "value": "Coca-Cola", "synonyms": [ "coca cola", "coke" ] }, { "value": "Beer", "synonyms": [ "beer" ] } ] } models.py: class Entity(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) class Value(models.Model): entity = models.ForeignKey(Entity, related_name='values', on_delete=models.CASCADE) value = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) class Synonymous(models.Model): value = models.ForeignKey(Value, related_name='synonyms', on_delete=models.CASCADE) synonymous = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) serializers.py: class ValueSerializer(serializers.ModelSerializer): synonyms = serializers.SlugRelatedField( many=True, slug_field='synonymous', queryset=Synonymous.objects.all() ) class Meta: model = Value fields = ('value', 'synonyms') def create(self, validated_data): synonyms_data = validated_data.pop('synonyms') value = Value.objects.create(**validated_data) for synonyomous_data in synonyms_data: Synonymous.objects.create(value=value, **synonyomous_data) return value class EntitySerializer(serializers.ModelSerializer): values = ValueSerializer(many=True) class Meta: model = Entity fields = ('id', 'name', 'description', 'values') def create(self, validated_data): values_data = validated_data.pop('values') entity = Entity.objects.create(**validated_data) for value_data in values_data: # How can I call the create method of values? pass return entity views.py @api_view(['GET', 'POST']) def entity_list(request, format=None): """ List all entities, or create a new entity. """ if request.method == 'GET': entities = Entity.objects.all() serializer = EntitySerializer(entities, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = EntitySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The … -
Django template keyword `choice_value` in no longer work in 1.11
There is a multiple checkbox in template, if value contain in render the choice will checked by default. It works well with 1.10. form.py: class NewForm(forms.Form): project = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Project.objects.filter(enable=True) ) template: {% for p in form.project %} <label for="{{ p.id_for_label }}"> <input type="checkbox" name="{{ p.name }}" id="{{ p.id_for_label }}" value="{{ p.choice_value }}" {% if p.choice_value|add:"0" in form.project.initial %} checked{% endif %}> <p>{{ p.choice_label }}</p> </label> {% endfor %} views.py: def order_start(request, order_id): if request.method == 'POST': form = NewForm(request.POST) if form.is_valid(): order.end_time = timezone.now() order.save() order.project = form.cleaned_data['project'] order.save() return HttpResponsec(order.id) else: form = NewForm(initial={ 'project': [p.pk for p in order.project.all()], }) return render(request, 'orders/start.html', {'form': form, 'order': orderc}) When I upgrade to Django 1.11, {{ p.name }} and {{ p.choice_value }} return nothing. I know 1.11 has removed choice_value, but how to solve this problem? 1.10 https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/ 1.11 https://docs.djangoproject.com/en/1.11/_modules/django/forms/widgets/ -
I can't connect to django server in browser.
Tried running it from local host but in cmd prompt its fine as i see "Quit the server with CTRL-BREAK.". But not connecting in browser. Also tried telnet to connect to that port, but failed. what could be the reason? can't be a proxy as even telnet is not workiingThis is the first basiic beginner level start for django. but the same thing, works in my office computer. pls hhelpenter image description here -
Mobile app for fetching server python data
I want to develop services or method to send the data over web and to mobile app as well.For now I am using Django Framework (Python code on server side) to get data on web page.I have developed web pages as well. Now I want to send same server data over Mobile App.So should I search for new web services or I can achieve the things using Django Framework. Please suggest libraries for REST/SOAP for python My mobile app will be developed in Android and iOS. Regards NM -
How limit a user to save database in django?
How do i restrict the user to save objects in db class model_name(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) user = models.ForeignKey(User) foo = models.CharField(max_length=51) i want to limit the foo only for 10 entries per user i am using mysql as a backend -
How to edit formset that has multiple forms inside related via generic foreign to the model of the current edit view?
In my recent project I had to create a generic model with a single file field, because the idea was to use multiple file uploads across multiple system models. For this I created this generic model with generic foreign key and in the add view I create a formset with the extra = 1 field and in the template via jquery I add forms inside my formset. In addition it works quietly, but I'm not able to adjust my edit view. In my edit view I try it: ModelGenericFormset = modelformset_factory( ModelsFileGeneric, form=AddModelsGenericForm ) query_files = ModelsFileGeneric.objects.filter( object_id=model_related_to_generic_model_with_file_field.id, ) files = ModelGenericFormset(queryset=query_files) and in request.post: files_form_set = ModelGenericFormset( request.POST, request.FILES ) for file_form in files_form_set: file = file_form.save(commit=False) setattr( 'upload_destination', 'path_to_upload' ) file.content_object = model_related_to_generic_model_with_file_field file.save() An observation: As this model where the file field is is an extremely generic model (for this reason the use of the generic foreign key), I also need at runtime (in the save in view after the post) to change the upload_to attribute of the field (this already Was fixed and works ok). I make this edition of the "upload_to" attribute. Because depending on the template to which I am sending multiple files, it … -
Connecting to external DB from django settings.py
We're searching for the best way to use different types of DBs in our Django project without defining them as Django DBs (the frameworks we're using keep changing and we want to have the most low-level client connection as possible). We're using django and would like to open several clients for external DBs which will be alive and available all the time (for example: aws-s3, mongoDB, elasticsearch). Currently, in the settings.py we create these connections and use them across the project. For example: From settings.py: MONGO_CLIENT = pymongo.MongoClient(MONGO_CLIENT_URI) And from views.py: from django.conf import settings Now we have the mongoClient available as: settings.MONGO_CLIENT If we would like to use this client in one of our project modules, we currently send it by reference. For example: res = myModule(mongoClient=settings.MONGO_CLIENT) * Please note that we prefer not to define the DBs as Django DBs. Now to the questions: I'm not sure this is the best way to-do it from memory and resources management perspectives since Django doesn't have any control of the connection to the DB? Is this the best way to send the db-clients between the modules? Thanks! -
Vue.js "npm run build" but Vue.js not bound to DOM / working
Newbie to Vue.js here. On Mac OS using versions: $ npm --version 4.6.1 $ vue --version 2.8.1 I'm using the webpack-simple init with the vue-cli for vue 2.0. I've created a folder within my Django project folder for vue stuff called frontend. Directory structure: $ tree -L 1 ../ ../ ├── README.md ├── asnew │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── settings.py │ ├── templates │ └── index.html │ ├── urls.py │ ├── views.py │ ├── wsgi.py ├── frontend │ ├── node_modules │ ├── package.json │ ├── src │ ├── App.vue │ ├── assets │ ├── components │ │ └── SearchPageResult.vue │ ├── main.js │ └── webpack.config.js ├── manage.py ├── media ├── requirements.txt ├── static └── staticfiles Then basically in my index.html Django template I have the following code: <script src="{% static 'js/vue/build.js' %}"></script> <div id="app"></div> Once rendered this turns into the full path: <script src="/static/js/vue/build.js"></script> which I create with npm run build and I verified does actually get loaded/imported by the browser. I run the heroku CLI as the devserver. I build like this: $ cd frontend $ npm run build > vue-asnew@1.0.0 build /Users/me/MyProject/frontend > cross-env NODE_ENV=production webpack --progress --hide-modules Hash: d5e16854b8f88beea3e9 Version: webpack … -
How to add highchart in my view.py?
Anyone have idea on how to add high chart in view.py? which mean my data are filter base on the python code and from the dataframe convert to highchart. -
KeyError at /login u'message'
def loginUser(request): if request.method != 'POST': return redirect('/') attempt = User.objects.validateUser(request.POST) if attempt['status'] == True: request.session['user_id'] = attempt['user'].id return redirect('/books') else: messages.add_message(request, messages.ERROR, attempt['message'], extra_tags="login") return redirect('/') KeyError at /login u'message' Request Method: POST Request URL: http://127.0.0.1:8000/login Django Version: 1.11 Exception Type: KeyError Exception Value: u'message' -
Django CRUD update object with many to one relationship to user
I followed along the awesome tutorial How to Implement CRUD Using Ajax and Json by Vitor Freitas. For my project I have an object with a many to one relationship with the user that I want users to be able to add and update. I can add the object, but when I try to update it throws a ValueError: Cannot query "Case object": Must be "User" instance. views.py def case_update(request, pk): case = get_object_or_404(Case, pk=pk) if request.method == 'POST': form = CaseForm(request.POST, instance=case) else: form = CaseForm(instance=case) return save_case_form(request, form, 'cases/includes/partial_case_update.html') It breaks when I try to save the edit, but I am struggling to see a way around this. To edit this case, I need the form to be an instance of this particular case as the user may have many cases. When I set the instance to user, nothing happens, when I remove the instance altogether it obviously just makes a copy of the case so I have two of the same cases. I can post more code if necessary. Thank you -
how to configure django with mysql using pymysql (python 3.5)
having much trouble getting mysql(5.6) to connect with django (1.11) using python 3.5.2 in ubuntu(16.04) venv. im trying to use pymysql because it works great with flask applications, just not django yet. mysqlclient failed install and has other dependencies (ive read django docs yes) so would prefer avoiding that module. this really should work since it works flawless in flask and others seem to have it working. heres what Ive tried and found: # first steps pip install pymysql mysql -u root -p CREATE DATABASE djang0 CHARACTER SET utf8 COLLATE utf8_bin; # manage.py try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass # settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djang0', 'USER': 'root', 'PASSWORD': 'mypasswd', 'HOST': '', 'PORT': '3306', } } # current models.py Post class for blog class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() image = models.ImageField(upload_to='uploads', blank=True) # error - full here https://dpaste.de/vtEH [Thu Apr 27 18:58:00.010964 2017] [wsgi:error] [pid 22811:tid 3049028416] [remote 192.168.0.3:52267] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. [Thu Apr 27 18:58:00.010967 2017] [wsgi:error] [pid 22811:tid 3049028416] [remote 192.168.0.3:52267] Did you install mysqlclient or MySQL-python? -
Can't understand relationship of Celery Tasks to Django
I am using Django to listen to voice commands. I was going to use Celery as a way to run a seperate process for listening, and a seperate process for executing commands. When I had set up Django with Celery, I had envisioned starting Django (./manage.py runserver) and having those two processes initiate at startup. But so far I see that the Celery app is started via the shell, and Django speaks to it seperately. A HUGE part of my learning curve here is understanding what relationship Django has to Celery. I had intended to have everything running within the Django environment -- ie, not having Django run beside Celery. Can someone tell me where I've become confused? -
Getting "AttributeError: 'str' object has no attribute 'regex'" in Django urls.reverse
As in the title, I'm getting AttributeError: 'str' object has no attribute 'regex' I've seen many valid answers to this, but none of them applied to my code as they identified issues in the urls.py file. My issue is in the views.py file. I get the exception when using reverse to generate a redirect URL: HttpResponseRedirect(reverse('changetracker:detail', args)) When I use 'changetracker:detail' in other functions, I don't get the exception. -
Django ORM poor performance compared to raw sql
I'm using Django ORM for data query and I get almost 2 million rows in this table.I tried app_count = App.objects.count() and from django.db import connection cursor = connection.cursor() cursor.execute('''SELECT count(*) FROM app''') The mysql slow_query log gave me Time: 2017-04-27T09:18:38.809498Z User@Host: www[www] @ [172.19.0.3] Id: 5 Query_time: 4.107433 Lock_time: 0.004405 Rows_sent: 1 Rows_examined: 0 use app_platform; SET timestamp=1493284718; SELECT count(*) FROM app; This query took avg more than 4 seconds, but when I used mysql client and mysql shell to do this query mysql> select count(*) from app; +----------+ | count(*) | +----------+ | 1870019 | +----------+ 1 row in set (0.41 sec) Just take me 0.4 second, 10X difference, Why and how to improve it. -
Basic URL Django Issue
This basic url issue is giving me a headache. I have two links I wish to take a fictitious user to: localhost/prediction and localhost/prediction/. The first works, the second doesn't with an error saying that the site doesn't exist. Any clue as to why? URl Patterns: urlpatterns = [ # ex: /prediction/ url(r'^', views.post_list), # ex: /prediction/<number>/ url(r'^(?P<number>[0-9]+)/$', views.show_body) ] View: def show_body(request, number): return HttpResponse(number) -
Selenium python ajax query during page load takes very long time to return
Its a simple page load with the following JS code: $(document).ready(function () { set_initial(); ajax_query(); }); It takes like 5 minutes for selenium to get back a response when the ajax query is executed. Any ideas why this would happen? -
error during Django 1.8 test with multiple databases
I'm moving a Django 1.8 project from a single database setup to a writer/reader setup. I ran into the issue described in Django bug 23718 but the work arounds described didn't seem to help. Has anyone run into similar issues? Relevant code segments are below: Router: class DatabaseRouter(object): """Router to handle separation of reads and writes.""" def db_for_read(self, model, **hints): """Reads go to a read replica.""" return 'read' def db_for_write(self, model, **hints): """Writes always go to default.""" return 'default' def allow_relation(self, obj1, obj2, **hints): """Allow relations bet/n objects in the same DB cluster.""" db_list = ('default', 'read') if obj1._state.db in db_list and obj2._state.db in db_list: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """All models end up in this pool.""" return True relevant DB settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASS, 'HOST': DB_WRITE }, 'read': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASS, 'HOST': DB_READ, 'TEST': { 'MIRROR': 'default', }, } } DATABASE_ROUTERS = ['my_project.routers.DatabaseRouter'] work around replication test case: class ReplicationTestCase(TestCase): @classmethod def setUpClass(cls): super(ReplicationTestCase, cls).setUpClass() connections['read']._orig_cursor = connections['read'].cursor connections['read'].cursor = connections['default'].cursor @classmethod def tearDownClass(cls): connections['read'].cursor = connections['read']._orig_cursor super(ReplicationTestCase, cls).tearDownClass() Anything pop out? I'm happy to provide stacktraces from … -
djano-filters return only one object after filtering
I`m using django-filters to filter in my app, however it returns me only one result after filtering. There are more objects in db and I can see them when not using filters. Thank you a lot in advance for any help! models.py from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class Bancnote(models.Model): Dollar= 'Dolar' Euro= 'Euro' TYPE_CHOICES = ( (Dollar, 'Dollar'), (Euro, 'Euro') ) type = models.CharField(max_length=11, choices=TYPE_CHOICES, default=HRYVNA) par = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(1000000) size = models.CharField(max_length=7) sign = models.CharField(max_length=20) desc = models.TextField(max_length=200) image = models.ImageField(upload_to='bons_images') def __str__(self): return str(self.par) + ' ' + self.type) filters.py from django import forms import django_filters from .models import Bancnote class BancnoteFilter(django_filters.FilterSet): type = django_filters.ChoiceFilter(choices=Bancnote.TYPE_CHOICES, widget=forms.RadioSelect(attrs={'class': 'radio'}), label='Choise', empty_label=None) class Meta: model = Bancnote fields = ['type'] views.py from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render, render_to_response from django.template import RequestContext from django.shortcuts import render from .models import Bancnote from .filters import BancnoteFilter def index(request): bons_list = Bancnote.objects.all().order_by('par') bons_filter = BancnoteFilter(request.GET, queryset=bons_list) return render(request, 'catalogue/index.html', {'filter': bons_filter}) def image(request): bons = Bancnote() variables = RequestContext(request, { 'bons': bons }) return render_to_response('catalogue/bon_detail.html', variables) urls.py from django.conf.urls import url from django.views.generic import DetailView from catalogue import views from catalogue.models import Bancnote urlpatterns = [ … -
looping through list in python changes order
I thought list order python is immutable. When I do the following, the order of the list changes. for v in values_list: v.is_connected = True How can I prevent this? -
Schedule Django Celery periodic tasks to run from time to other time
How can I accomplish to run Django Celery tasks to be running only from Mon to Friday and on those days only from 9am to 5pm EST. celery.py from celery.schedule import crontab app.conf.beat_schedule = { 'compute-every-5-seconds': { 'task': 'sum', 'schedule': crontab(), }, } What parameters should I add to crontab() that it would run those days and between only those hours?