Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrating elasticsearch connection pooling in Django
I have a django application that stores status info of lots of sensors and I'm trying to use elasticsearch to store all of the status data, for further analysis. I have used elasticsearch a lot in Python scripts in general. My question is how to integrate elasticsearch-py/elasticsearch-dsl connection pooling into a django application. I would like to not create a connection for every request. I'm actually trying to embeed it into MyAppConfig inside apps.py but I'm not sure if it's a good idea. Any help? -
Celery TypeError on get_scheduler
Trying to setup Celery Running Django==1.10.2 and celery==4.0.2 with Supervisor but am getting this error on celery_beat Traceback (most recent call last): File "/home/user_one/venv/app_one/bin/celery", line 11, in <module> sys.exit(main()) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/__main__.py", line 14, in main _main() File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 281, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 480, in handle_argv return self.execute(command, argv) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/celery.py", line 412, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 285, in run_from_argv sys.argv if argv is None else argv, command) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 368, in handle_argv return self(*args, **options) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/base.py", line 244, in __call__ ret = self.run(*args, **kwargs) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/bin/beat.py", line 107, in run return beat().run() File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 79, in run self.start_scheduler() File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 98, in start_scheduler print(self.banner(service)) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 120, in banner c.reset(self.startup_info(service))), File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/apps/beat.py", line 130, in startup_info scheduler = service.get_scheduler(lazy=True) File "/home/user_one/venv/app_one/lib/python3.5/site-packages/celery/beat.py", line 567, in get_scheduler lazy=lazy, TypeError: 'module' object is not callable app/settings.py BROKER_URL = 'redis://:{}@{}:{}/{}'.format(redis_pass, redis_host, redis_port, redis_db) CELERY_RESULT_BACKEND = 'redis://:{}@{}:{}/{}'.format(redis_pass, redis_host, redis_port, redis_celery_results_db) CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' I've used Celery successfully in other projects before but not with Django but I've followed the … -
Dynamic table creation with django
i am currently working on a DJANGO project and it happens that i need to generate a dynamic table in my template containing data from my models. The page contains some buttons (modify, delete, show full details) and the table itself my problem is i want to link the rows with the buttons such as when i click a button i can detect which row is selected then do the appropriate action (such as modifying the data or deleting it from the database) how can i do that -
elasticsearch python TransportError 404
It's hard to put this in a visible form, but I am making a request to the standard localhost:9200 from python using the API. The first test is made from Django using the development server running on 0.0.0.0:8000. This returns fine. The second is done from Django through uWSGI and nginx. It returns: TransportError(404, u'{"_index":"xxx","_type":"xxx","_id":"xxx","found":false}') For the exact same request. Both are pointing to localhost:9200. It doesn't make sense to me that the development server has some special privilege. It is definitely connecting because: A) I display a list of results first, then detail for each item. The list displays and shows all the results fine in both cases, but the detail view fails. B) It is a TransportError, not a ConnectionError, meaning that it searched and returned no results, unless I am wrong. Thanks in advance. -
How to remove label?
How to remove label from MultipleChoiceField in template? forms.py: class RequirementAddForm(forms.ModelForm): symbol = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,) class Meta: model = Requirement fields = ('symbol',) template.html: {{ form }} -
How to install libmaxminddb on heroku
The libmaxminddb improves the performance of geo location look ups. But how can I install it on heroku? -
'django.template.context_processors.request' issue with django-tables2 and django-admin-tools
I'm having an issue when trying to render a PDF through xhtml2pdf in Django(1.10.4) when using django-admin-tools(0.8.0) & django-tables2(1.5) together. I've done enough reading to understand the basis of what's going on but have not idea how to fix it. I think it's got something to do with the django-admin-tools custom loaders. Link to the exception I'm getting from django-tables. This SO question led me to asking a question. The gist of what I'm trying to do is create a custom Admin 'action' through the drop-down box of my AdminModel in the django-admin interface that turns the queryset given into a PDF document. According to the django-tables2 docs the render() function takes 3 arguments (request, 'template_name.html', {'people': Person.objects.all()}). So I added a queryset to my context_dict and tried using it in a for loop in the template below but no dice. The template renders the html to pdf just fine without django-tables2 but if I try to convert the tables to PDF I get the following... Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:9999/admin/research/labsample/ Django Version: 1.10.4 Python Version: 3.5.2 Installed Applications: ('admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_tables2', 'import_export', 'chemicals', 'suppliers', 'customers', 'recipes', 'research') Installed … -
Django oscar paypal not working
so I am trying to set up django-oscar-paypal with django-oscar. So, everything works fine, the paypal express checkout page shows correctly, then it redirects back to the store and when i click the place order button, it redirects to an empty basket, with no transaction being recorded in the dashboard, except for the express dashboard, which shows success. My guess is there is a session loss, or I need to edit the checkout view somehow for it to post the request, but i can't find anywhere on how to do that, and copying the one from the sandbox isn't helpful. If anybody managed to make it work I would be very grateful for help. -
Django formset UpdateView won't let me upload files
I'm trying to create an UpdateView view with multiple inline formsets. It's working almost fine as I can add or remove files and images, but for some reason it won't accept any file/image. For example, if I add a second File in a Publication and upload a file, it will return a form_invalid function stating that This field is required next to the FileField. Same thing with images - I can't add any new image or I can't even change any image to another file as it'll say that this field is required. Other than that, I can change all the Publication fields and I can also change File's title, description and version and it'll save properly, but when I add a new File/Image or just change the file it uses, then it won't do anything and it'll just return an invalid form function. #models.py class Publication(models.Model): title = models.CharField('Tytul', max_length=100) author = models.ForeignKey(User, verbose_name=('Author'), blank=True, default=0) pub_date = models.DateTimeField('Data publikacji', default=datetime.now) mod_date = models.DateTimeField('Data ostatniej modyfikacji', default=datetime.now) description = models.CharField('Opis', max_length=450) slug = models.SlugField(max_length=40, unique=True) category = models.ForeignKey(Category, verbose_name=('Kategoria'), default=0, related_name='publication') video = EmbedVideoField(blank=True) class File(models.Model): title = models.CharField('Tytul', max_length=100) version = models.CharField(verbose_name=u"Wersja", max_length=100) author = models.ForeignKey(User, verbose_name=('Author'), blank=True, … -
Querying the Sqlite database for a user with username "x" using the standard django.contrib.auth.models.User model
I'm trying to wrap my head around an issue I'm having. I want to present the users with a page in which they can look up a user by entering his username. Yet I can't wrap my head around how to do this. Do I provide a function in my view in which a query is executed that retrieves a user from the database? For example retrieve his username or id and go to his profile page? I can't seem to grasp how to do this, I have been looking for examples on this but I can't find anything so I hope someone here can help me out! -
Writing to a set of objects as a single dictionary in Django REST Framework
I have created a set of models to allow users to define custom fields for certain objects within a Django project. This allows users to store data which is pertinent to their specific use case without modifying the database schema. For example, the project includes a built-in Site model which has a name, address, etc. A user could create a custom field for this model if they also wanted to store, for example, the named point of contact for each site. First, the user creates a custom field and assigns it to the model(s) they want to have that field. This is represented by a CustomField object. (A simplified version of the model is provided here. The full source is available here for anyone interested.) class CustomField(models.Model): obj_type = models.ManyToManyField(ContentType, related_name='custom_fields', verbose_name='Object(s)') type = models.PositiveSmallIntegerField(choices=CUSTOMFIELD_TYPE_CHOICES, default=CF_TYPE_TEXT) name = models.CharField(max_length=50, unique=True) label = models.CharField(max_length=50, blank=True) A second model holds the custom field data for each object: class CustomFieldValue(models.Model): field = models.ForeignKey('CustomField', related_name='values') obj_type = models.ForeignKey(ContentType, related_name='+', on_delete=models.PROTECT) obj_id = models.PositiveIntegerField() obj = GenericForeignKey('obj_type', 'obj_id') serialized_value = models.CharField(max_length=255) So in our example, we would create a CustomField named point_of_contact for the Site model, and a CustomFieldValue instance for each Site which has … -
How to serialize all fields of django model, but validate only particular one?
Imagine I have model and in my API method I want behaviour like "return all model fields if instance exists else return some message". So I want my serializer to validate only by id (not all fields, because I have only id parameter in my method), but return all fields of the model. How can I implement this? Should I have 2 separate serializers for validation and for serialization? -
Output the values of the variables of django rest framework
hello i have project on django rest framework and angularjs often need for debugging output some variable of backend, Is there simple a way output the values of the variables ? -
How to append link to <a> element using Javascript
I want to add href to an a html element from class of another element. It might also be good to know that i am using Django.As well i dont want the second url to be visible, when the character is not selected yet. Firstly i have this list: <ul> <a class="1" id="tablink">A</a> <a class="2" id="tablink">B</a> ... </ul> if list from the first ul is selected, i want the class of the list (example: A) to add to href element to all links in another ul: <ul> <a href="{% url id=id character= <!--here i want the number selected to be inserted--> %}">One</a> <a href="{% url id=id character= <!--here i want the number selected to be inserted--> %}">Two</a> ... </ul> Thank you! -
Django 1.11 download file chunk by chunk
In my case I have the Django 1.11 server acting as a proxy. When you click "download" from the browser, it sends a request to the django proxy that downloads files from another server and processes them, after which they must "send" them to the browser to allow the user to download them. My proxy downloads and processes the files chunks by chunks. How can I send chunks to the browser as they are ready so that the user finally downloads a single file? In practice I have to let you download a file that is not yet ready, like a stream. def my_download(self, res) # some code file_handle = open(local_path, 'wb', self.chunk_size) for chunk in res.iter_content(self.chunk_size): i = i+1 print("index: ", i, "/", chunks) if i > chunks-1: is_last = True # some code on chunk # Here, instead of saving the chunk locally, I would like to allow it to download it directly. file_handle.write(chunk) file_handle.close() return True Thank you in advance, greetings. -
Django 1.10 UUIDField returns either string or UUID
While upgrading from Django 1.9.13 to Django 1.10.7 I encountered a weird issue with Django's native UUIDField. We use this UUIDField on our custom User model like: username = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) In 1.9 this always returns a UUID instance. In 1.10 this returns a string when creating a new model instance. Compare the following test examples: 1.9.13 >>> u = User.objects.last() >>> u2 = UserFactory() >>> u3 = User.objects.create() >>> u.pk UUID('e7e0f87d-1ed4-4293-829f-b0b745ccd676') >>> u2.pk UUID('f8e9a4a9-2265-4cd7-9813-00ffe7fd922a') >>> u3.pk UUID('0cb736d7-f8a0-4057-9c89-44fa114f4f82') 1.10.7 >>> u = User.objects.last() >>> u2 = UserFactory() >>> u3 = User.objects.create() >>> u.pk UUID('e7e0f87d-1ed4-4293-829f-b0b745ccd676') >>> u2.pk 'f8e9a4a9-2265-4cd7-9813-00ffe7fd922a' >>> u3.pk '0cb736d7-f8a0-4057-9c89-44fa114f4f82' This difference gives issues with various unittests. I can work around it by forcing both to string, but I wish to understand why UUIDField behaves the way it does as it feels inconsistent. -
Django object manager 'lower' parameter
I am trying to filter out a queryset based on if one of its field names is in a list of lower case values. The trouble is that some of these field values have capital letters, so I can't do all_listings = all_listings.objects.filter(make__name__in=makes) Is there a possible way to say something along the lines of all_listings = all_listings.objects.filter(make__name__lower__in=makes) -
What is better Django channel or RabbitMQ web mqtt plugin?
I've one web application listening on particular channel using websocket.I've used Django web channel for live notifications. RabbitMQ provides web mqtt plugin for socket communication. My question is what to use ? Which is better ? Pros and Cons of both.Any help would be great. -
MultipleChoiceField create multiple objects
I use MultipleChoiceField in my form. I want to add all selected values to database, but next code which I use add only last value which user select. I tried in my view create multiple number objects. Where I did mistake? models.py: class Requirement(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) symbol = models.CharField(_('Symbol'), max_length=250) name = models.CharField(_('Name'), max_length=250) forms.py: class AddForm(forms.ModelForm): symbol= forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,) class Meta: model = Requirement fields = ('symbol',) REQUIREMENTS_CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ) views.py: def requirement_add(request): data = dict() if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): list = dict(REQUIREMENTS_CHOICES) # {'C': 'Name C', 'A': 'Name A', 'B': 'Name B'} symbols = form.cleaned_data.get('symbol') # ['A', 'B', 'C'] requirement = form.save(commit=False) for symbol in symbols: requirement.symbol = symbol requirement.name = group_requirement_list[symbol] requirement.save() data['form_is_valid'] = True requirements = Requirement.objects.filter() context = {requirement': requirement, 'requirements': requirements} data['html_requirement'] = render_to_string('project/requirement_list.html', context) else: data['form_is_valid'] = False else: form = AddForm() context = {'form': form} data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request) return JsonResponse(data) -
Stripe Connect with Python Django
I'm trying to set up stripe connect in a Python/Django application so that I can have a number of contractors taking work from a site and being paid directly. I'm trying to get authorisation by getting a token for a new contractor. I've got the following view: def authorise(request): site = 'https://connect.stripe.com' + '/oauth/authorize' params = { "response_type": "code", "scope": "read_write", "client_id": STRIPE_CLIENT_ID } # Redirect to Stripe /oauth/authorize endpoint url = site + '?' + urllib.urlencode(params) return redirect(url) This will take me into Stripe to setup a connection but when I select the stripe connect button on the Stripe site I get: 127.0.0.1 refused to connect. My callback URL is 127.0.0.1/contractor/stripe_contractor_callback and the url call is: http://127.0.0.1/contractor/stripe_contractor_callback?scope=read_write&code=my_text_code What am I missing? -
Customize context data
I have three class. The first class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) the second class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' and the third class CustomerPerceptionIndexView(CustomerMixin, PerceptionIndexView): template_name = 'loanwolf/customers/perceptions.html' pjax_template_name = 'loanwolf/customers/perceptions.pjax.html' def get_context_data(self, **kwargs): context = super(CustomerPerceptionIndexView, self).get_context_data(**kwargs) filter_perceptions= (Perception.objects.filter(loan__request__customer__pk=self.customer.pk)) resultant = [r for r in context['results'] if r['object'] in filter_perceptions] context["resultant"] = resultant context["state"] = Perception.state #This has not solved my problem return context Actually, the context of CustomerPerceptionIndexView did not contain the attribute state. I would like to get access state attribute from Perception class in the context of CustomerPerceptionIndexView class. How could I do such thing? Thanks in advance! P.S. To be clear, I want to fix the error AttributeError: 'str' object has no attribute 'state'. I don't think I have to add 'state' like context["state"] = Perception.state. Furthermore, please let me know if I have to add something in the question. I don't have a lot of experience with Django, and your … -
django-rest-auth: what is access_token and what code
For someone this can be trivial question but for me is not because i am beginer with django. I am using django-rest-auth to make restful registration of users. I succeed with standard (email, password) authentication and email confirmation (verification). But problem is in social login because i want to allow users to login with facebook (google+) account. I know how to make facebook App and get its SOCIAL_AUTH_FACEBOOK_KEY and SOCIAL_AUTH_FACEBOOK_SECRET. What i don't know is how to use api call to make login. By docs http://django-rest-auth.readthedocs.io/en/latest/api_endpoints.html it says url is /rest-auth/facebook/ and also i need to provide access_token and code. My question is what is access_token and what is code parameter and how to get them so i can try example with curl. Thank you. -
Django rest framework, set the api response Content-Encoding to gzip
Am working on django project, that act as a distribution server to other server when they request for some certain data through and api call, this data is in form of JSON and is very large. So i was thinking is there any way i can set my DRF APIView response to serves the outputted JSON response with gzip set for the Content-Encoding so as to reduce the size of the content, when consuming by the other servers. Currently my application is running on gunicorn with nginx on the front as a proxy. -
How to use django admin display some specific order data
I have model below class SynonymQuery(models.Model): original_query = models.CharField(max_length=30,verbose_name = "query") insert_time = models.DateField(auto_now_add=True) admin below class synonym_queryAdmin(admin.ModelAdmin): ordering = ('update_time','original_query') data 1.bcd time 2.abc time 3.bcd time if No.1 data is insert last time, I want to show data all the same original_query as No.1 in the header lines. I try to use ordering function, but result are incorrect. -
How to customize Django messages?
I'm trying to integrate this snippet into our Django project: It's just custom HTML and CSS for messages. The html looks like this: <div class="bs-calltoaction bs-calltoaction-success"> <div class="row"> <div class="col-md-9 cta-contents"> <h1 class="cta-title">Its a Call To Action</h1> <div class="cta-desc"> <p>Describe the action here.</p> <p>Describe the action here.</p> <p>Describe the action here.</p> </div> </div> <div class="col-md-3 cta-button"> <a href="#" class="btn btn-lg btn-block btn-default">Go for It!</a> </div> </div> </div> So if I want to integrate it with messages framework, I can do: {% for message in messages %} <div class="bs-calltoaction bs-calltoaction-{{ message.tags }}"> <div class="row"> <div class="col-md-9 cta-contents"> {{ message }} </div> <div class="col-md-3 cta-button"> <a href="#" class="btn btn-lg btn-block btn-default">Go for It!</a> </div> </div> </div> {% endfor %} But I would like to specify header <h1> and list of sub-messages <p> so it would be: {% for message in messages %} <div class="bs-calltoaction bs-calltoaction-{{ message.tags }}"> <div class="row"> <div class="col-md-9 cta-contents"> <h1 class="cta-title">{{ message.title }}</h1> <div class="cta-desc"> <p>{{ message.submessages.0 }}</p> <p>{{ message.submessages.1 }}</p> </div> </div> <div class="col-md-3 cta-button"> <a href="#" class="btn btn-lg btn-block btn-default">Go for It!</a> </div> </div> </div> {% endfor %} Is it possible using Django messages?