Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery periodic task for many objects
In My models I have Campaign entity and User entity .. I want to take the minutes of the created field of the Campaign entity and run an hourly task with it for every campaign, the celery task should get the users visiting the campaign in the last hour and choice one of them randomly to win money from the campaign sold . Knowing that the periodic task should be a function called in celery.py file. What should I do ? Thanks in advance. -
Mongo Django GridOut object has no attribute 'readlines'
I need to use method readlines() to standardize my gridfs but GridFS doesn't have readlines(). The error is AttributeError: GridOut object has no attribute 'readlines' I tried to use different ways instead but it doesn't return the result that I want to read my file. read().split("\n") or line = f.readline() while line: print line line = f.readline() or f = open('myfile.txt') for line in iter(f): print line Does anyone have any idea how I implement readlines in GridFS? Thanks -
Celery with Supervisord workers are not working Isolated
.conf file [program:task1] directory=/home/ubuntu/proj1 command=/usr/bin/python3 /usr/local/bin/celery -A proj1 worker -l info --concurrency=10 -n proj1_worker@%%h user=ubuntu numprocs=1 stdout_logfile=/var/log/proj1_celeryd.log stderr_logfile=/var/log/proj1_celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 priority=998 [program:task2] directory=/home/ubuntu/proj2/ command=/usr/bin/python3 /usr/local/bin/celery -A proj2 worker -l info --concurrency=10 -n proj2_worker@%%h user=ubuntu numprocs=1 stdout_logfile=/var/log/proj2_celeryd.log stderr_logfile=/var/log/proj2_celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 priority=998 [group:celeryworkers] programs=task1,task2 proj1_worker and proj2_worker are not getting isolated. At first, always proj1_worker is called even I called proj2_worker I don't know where I am going wrong. Kindly assist. Thank you in advance -
how can I send some information from tornado server to another tcp server
I have a python tornado websocket server called as app.py. here I am getting some information from the client side or browser, which is written in webrtc.I am getting all the information in app.py file as expected but not I want to send those data to some other TCP server.Here In these case my tornado server aap.py will act as a client for other TCP server.I read some Tornado TCP Client example but not able to understand.here is some Idea about these http://www.tornadoweb.org/en/stable/tcpclient.html .I am new in these technology, please help me someone to solve these problem. /app.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os import logging import tornado.ioloop import tornado.web import tornado.httpserver import ssl from tornado.ioloop import IOLoop from tornado.options import define, options from tornado.web import Application, RequestHandler from tornado.websocket import WebSocketHandler sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23) rel = lambda *x: os.path.abspath(os.path.join(os.path.dirname(__file__), *x)) class MainHandler(RequestHandler): def get(self): self.render('index.html') class EchoWebSocket(WebSocketHandler): clients = [] def open(self): logging.info('WebSocket opened from %s', self.request.remote_ip) EchoWebSocket.clients.append(self) def on_message(self, message): logging.info('got message from %s: %s', self.request.remote_ip, message) #getting information here, want to send these information to a TCP server. for client in EchoWebSocket.clients: if client is self: continue client.write_message(message) def on_close(self): logging.info('WebSocket closed') EchoWebSocket.clients.remove(self) def … -
Can i replace the recognizer.train() by some other means to reduce execution time
How to train images in cv2 to save time? ie, I need to run recognizer.train() function only once. Is the result can be saved in db or some means so that i can take it during the time of comparing images. -
Save processed image in Django
I'm having trouble implementing the solution suggested here: PIL thumbnail is rotating my image? My case is a little different because I'm working with user-uploaded files. Here's my view: from PIL import Image, ExifTags def add_work_image(request, work_id=None): image = WorkImage() image.owner = request.user.profile image.sort_index = int(request.POST.get('image_order')[0]) source_image = request.FILES.get('image_file') try: opened_image = Image.open(source_image) if hasattr(opened_image, '_getexif'): # only present in JPEGs for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation]=='Orientation': break e = opened_image._getexif() # returns None if no EXIF data if e is not None: exif=dict(e.items()) orientation = exif[orientation] print("***** orientation") print(orientation) if orientation == 3: opened_image = opened_image.transpose(Image.ROTATE_180) elif orientation == 6: opened_image = opened_image.transpose(Image.ROTATE_270) elif orientation == 8: opened_image = opened_image.transpose(Image.ROTATE_90) opened_image.save(...) # <--- Getting lost here image.image = opened_image except: image.image = source_image if work_id: work = get_object_or_404(Work, pk=work_id) image.work = work image.save() return JsonResponse({ 'image_src': image.get_absolute_url(size='work_image'), 'image_id': image.pk}) I'm unfamiliar with how Django / Python handles uploaded files. What am I missing here? -
How to design an assessment app with tests, questions and answer choices in django rest framework?
I have build a "content" app with "Tests" model having "Passages" model having "Questions" model having "Answer Choices" model. The answer choice are either correct or incorrect. The "assessment" app has "Answers" model that stores user and answer choice combination. I have created rest framework end points for adding the content. I have manually added few entries of answers model with user and answer choice combinations. Data is like: Test1 Passage1 Question1 AnswerChoice1 False AnswerChoice2 True AnswerChoice3 True AnswerChoice4 True Answer User1, AnswerChoice1 User1, AnswerChoice2 User1, AnswerChoice3 Would it be possible to generate the report for User1 on Test1? I am guessing i would need to check if users answer choices are right compared to the right and wrong values in AnswerChoice model. I also need to create an end point for the same like report/{test_id} Test1 Passage1 Question1 result:Wrong Question2 ... Question... Passage... -
how to update django cached_property
I would like to use @cached_property on model property to avoid too much db access. class AttrGroup(models.Model): ... @cached_property def options(self): options = AttributeOption.objects.filter(group_id=self.id) return options ... This works fine. i want to use the following function to update the value of options.But how should i do it? for property decorator, there is setter for it. def _set_options(self, value): for option in value: AttributeOption.objects.create(group_id=self.id, option=option.get('option')) -
Add extra html to all default fields
I have a couple fields in a django Model and want to append a range slider to each default field. I try to use crispy helper to create a div using layout but this just apply to one field. Its a bootstrap form-group with a col-md-2 label, the slider in a col-md-8, and a IntegerField in col-md-2. Initial form-inline with label and number field work, but I can not insert the slider in any field. -
Oauth token check user validation
I have django REST authentication with django-oauth-toolkit. I have two api one for public and another one for API. The private API will be called by internal system. How can I see what user is this and get the user id based on token ? Thanks -
How to add commas in thousands and to show decimal upto 2 places on X/Y axis in Angular chat JS?
How to add commas in thousands and to show decimal upto 2 places on X/Y axis in Angular chat JS ? <div class="col-md-6" ng-if="$ctrl.projection_data.chart_type == 'bar'"> <canvas id="bar" class="chart chart-bar" style="height: 400px" chart-series="$ctrl.projection_data.series" chart-data="$ctrl.projection_data.data" chart-labels="$ctrl.projection_data.labels"> </canvas> </div> -
UserProfile update form not saving data
I'm having trouble with my django userprofile update form. Problem: When i click on the "update" button on my html, my updates are not saved. In my simple web-app, i've created a login system alongside a UserProfile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='related_profile') organization = models.CharField(max_length=100) bio = models.TextField() classes = models.TextField() year_of_grad = models.CharField(max_length = 4) upload = models.FileField() def __str__(self): return self.user.username Then, I wanted to create a page that would allow me to edit both the User attributes (first_name, last_name, email and username) as well as the attributes of Profile model. So i created 2 forms, one for updating the user attributes, the other for updating the profile attributes. forms.py: class UpdateProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('organization', 'bio', 'classes', 'year_of_grad', 'upload',) def save(self, user=None): user_profile = super(UpdateProfileForm, self).save(commit=False) if user: user_profile.user = user user_profile.save() return user_profile class UpdateUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def save(self, user=None): user_ori = super(UpdateUserForm, self).save(commit=False) if user: user_ori.user = user user_profile.save() return user_ori So, in my views.py: def update_user(request): user_profile = Profile.objects.get(user=request.user) if request.method == "POST": update_user_form = UpdateUserForm(data=request.POST, instance=request.user) update_profile_form = UpdateProfileForm(data=request.POST, instance=user_profile) if update_user_form.is_valid() and update_profile_form.is_valid(): user = update_user_form.save() … -
Django auto-generated unique field failing validation on form edit
I am attempting to reuse my create form (EntryForm) for editing a model in Django. My Entry model has a unique slug that is generated on save. This works fine when creating an Entry, but shows the following error when I attempt to edit it: Entry with this Slug already exists. I saw several similar questions, but most were failing to set instance= when instantiating the form. I'm pretty sure I'm doing that part correctly. I've removed other model fields from the code below for clarity. Here is my model: class Entry(models.Model): title = models.CharField(max_length=128, blank=True) slug = models.SlugField(unique=True, blank=True) def save(self, *args, **kwargs): if not self.title: self.title = self.date.strftime('%B %-d, %Y') self.slug = slugify(self.title) super(Entry, self).save(*args, **kwargs) My view: def edit_entry(request, entry_slug): entry = get_object_or_404(Entry, slug=entry_slug) form = EntryForm(instance=entry, label_suffix='') if request.method == 'POST': form = EntryForm(request.POST, instance=entry, label_suffix='') if form.is_valid(): form.save(commit=True) return index(request) else: print(form.errors) return render(request, 'journal/entry/form.html', {'form': form}) My form: class EntryForm(forms.ModelForm): title = forms.CharField(required=False, max_length=128, label="Title (defaults to date)") slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Entry exclude = () Any ideas? -
My form with a ModelMultipleChoiceField is not saving data.
In the admin panel, I can add Persons to my CompleteClass model. There is a M2M relationship between CompleteClass and Person. But, my form doesn't work as it should. The pub_date will update, and I can save the head_count, but not the ModelMultipleChoiceField (persons) -- it will not save. models.py class Person(models.Model): name = models.CharField(max_length=255) persona_description = models.CharField(max_length=255) def __str__(self): return self.name class CompleteClass(models.Model): persons = models.ManyToManyField(Person) class_name = models.CharField(max_length=255) class_head_count = models.IntegerField() class_pub_date = models.DateField() def __str__(self): return '%s %s' % (self.class_name, self.class_head_count) def save_complete_class(self): self.class_pub_date = timezone.now() self.save() class Meta: ordering = ('class_pub_date',) Here is views.py: def class_new(request): if request.method == "POST": form = CompleteClassForm(request.POST) if form.is_valid(): complete_class = form.save(commit=False) complete_class.class_pub_date = timezone.now() complete_class.save() form.save_m2m() return redirect('class_detail', pk=complete_class.pk) else: form = CompleteClassForm() return render(request, 'app/class_edit.html', {'form': form}) and forms.py class CompleteClassForm(forms.ModelForm): class Meta: model = CompleteClass fields = ('class_name', 'class_head_count',) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(CompleteClassForm, self).__init__(*args, **kwargs) self.fields['class_persons']=forms.ModelMultipleChoiceField(queryset=Person.objects.all()) I've read through the documentation and used the save_m2m since i've set commit=false. The POST data contains person data, but it's not being written to the database. I'm stumped. Please help! -
Implement mosquitto jwt authentication with django rest framework server
I have implemented mosquitto jwt authentication using django rest framework jwt as sever. In configuration i see no error, but when i run mosquitto and django i have some error, Here in django terminal , "POST /api-token-auth/ HTTP/1.1" 400 79 and in mosquitto.conf terminal, 1490583684: mosquitto version 1.4.11 (build date 2017-03-08 15:27:51+0700) starting 1490583684: Config loaded from /etc/mosquitto/mosquitto.conf. 1490583684: |-- *** auth-plug: startup 1490583684: |-- ** Configured order: jwt 1490583684: |-- with_tls=false 1490583684: |-- getuser_uri=/api-token-auth/ 1490583684: |-- superuser_uri=/superuser 1490583684: |-- aclcheck_uri=/acl 1490583684: |-- getuser_params=(null) 1490583684: |-- superuser_params=(null) 1490583684: |-- aclcheck_paramsi=(null) 1490583684: Opening ipv4 listen socket on port 1883. 1490583684: Opening ipv6 listen socket on port 1883. 1490583749: New connection from 127.0.0.1 on port 1883. 1490583749: |-- mosquitto_auth_unpwd_check(andri) 1490583749: |-- ** checking backend jwt 1490583749: |-- url=http://127.0.0.1:8000/api-token-auth/ 1490583749: |-- data=topic=&acc=-1&clientid= 1490583749: |-- getuser(andri) AUTHENTICATED=0 by none 1490583749: Socket error on client <unknown>, disconnecting. Here my mosquitto.conf auth_plugin /etc/mosquitto/auth-plug.so auth_opt_backends jwt auth_opt_http_ip 127.0.0.1 auth_opt_http_port 8000 #auth_opt_http_hostname example.org auth_opt_http_getuser_uri /api-token-auth/ auth_opt_http_superuser_uri /superuser auth_opt_http_aclcheck_uri /acl Can anyone help me about my error ? -
Django how to authenticate credentials via a desktop application
I am new to django and web dev in general (reference for my skill level) and I want to be able to authenticate a users credentials via a desktop application. How would I go about doing this? -
upload multiple image to rental resource
There is a form for posting/listing rent. Form includes posting rental information along with multiple image upload feature in the same form. What will be the best way to handle multiple image upload? Should i write different multiple image upload view? How should i handle the upload view? Here is my code models.py class Rental(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=300, blank=False, null=False) phone_number = models.PositiveIntegerField(null=False, blank=False) renter = models.CharField(choices=RENTER_CHOICES, max_length=1, default=RENTER_CHOICES[0]) property_type = models.CharField(choices=PROPERTY_TYPE, max_length=1, default=PROPERTY_TYPE) def __str__(self): return self.name def user_directory_path(instance, filename): return 'rent_{0}/{1}'.format(instance.rent.id, filename) class Gallery(models.Model): rent = models.ForeignKey(Rental, related_name="galleries") image = models.FileField(upload_to=user_directory_path, null=True, blank=True) tag = models.CharField(max_length=1, choices=TAGS, null=True, blank=True) def __str__(self): return self.image.name class GallerySerializer(serializers.ModelSerializer): # rent = serializers.ReadOnlyField() class Meta: model = Gallery fields = ('image', 'tag',) class RentalSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') galleries = GallerySerializer(many=True) class Meta: model = Rental fields = ('__all__') # fields = ('user', 'name', 'phone_number','rent',) def create(self, validated_data): galleries = validated_data.pop('galleries') rental = Rental.objects.create(**validated_data) print ('rental', rental) for image in galleries: Galleries.objects.create(rent=rental, **image) return rental class RentAPIView(APIView): serializer_class = RentalSerializer parser_classes = (FormParser, MultiPartParser,) def post(self, request, token=None, format=None): """ create a new rent if token is None else update existing rent """ rent = None if not token is … -
Wagtail streamtext paragraph unedtiable in demo blog causing django app to crash
I am attempting to follow the demo blog project, to get up to speed with wagtail. I've installed wagtail into an existing django app. http://wagtail-nesting-box.readthedocs.io/en/latest/tutorial_blog/ I installed nesting box: pip install wagtail-nesting-box I added the following into my settings.py INSTALLED_APPS = [ 'wagtail_box', 'wagtail_box.blog', 'wagtail.contrib.settings', ] I migrated the changes within my virtualenv using: python manage.py migrate I created a blog page as per the instructions, then a child item blog post. The blog post editor loads, and I see the various fields, including the body... However when I click the paragraph element , a blue box appears, but I am unable to edit it. If I click the H2 element, I can edit this. But the Paragraph element, is locked and I can not add any text to it. If I attempt to save the page with nothing in the paragraph element I receive the following error: ValueError at /cms/pages/7/edit/ invalid literal for int() with base 10: '' Which i've traced back to this code, in stream_block.py int(data['%s-%d-order' % (prefix, i)]), How can I unlock the paragraph element so that it's editable? How can I generate a more user friendly error? So the django app doesn't crash if it … -
NoReverseMatch at / Django 1.10
I`m using Django 1.10 and I getting this error: NoReverseMatch at / Reverse for 'views.product_detail' with arguments '()' and keyword arguments '{'pk': 1}' not found. 0 pattern(s) tried: [] This is my index.html template: {% for pr in product %} <li> {{ pr.pk }} <a href="{% url 'views.product_detail' pk=pr.pk %}"> {{ pr.name }} </a> || {{ pr.description }} || <img src="{{ pr.image.url }}"> </li> {% endfor %} My Main project urls.py is: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include('products.urls') ), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) My App urls.py is: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.hello_world, name='hello'), url(r'^product/(?P<pk>[0-9]+)/$', views.product_detail,name='product_detail'), ] My views.py is: from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.shortcuts import render, get_object_or_404 from .models import Product # Create your views here. def hello_world(request): product = Product.objects.order_by('id') template = loader.get_template('index.html') context = { 'product': product } return HttpResponse(template.render(context, request)) def product_detail(request, pk): product = get_object_or_404(Product, pk=pk) template = loader.get_template('product_detail.html') context = { 'product': product } return HttpResponse(template.render(context, request)) the error message is: Error message Thanks for your help !!! -
how can we append extra fields dynamically in serializer.py using request object
http://127.0.0.1:8000/?words=anger and i want to add 'anger' to the field serializer dynamically. from .models import Synonym from rest_framework import serializers class SynonymSerializer(serializers.ModelSerializer): class Meta: model = Synonym fields = ('word',) -
Volley requests not working with Django Sessions
I have a Django script running on the server that creates session variables for every request sent to the server. The script returns a specific value based on the previous stored session variables. When I tested the script on the browser, the session on Django worked as per the requirement. However, while using Volley to send the same request, the script considers every request as a new request without taking previous session variables into consideration. StringRequest stringRequest = new StringRequest(Request.Method.GET,Send_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Response(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); requestQueue.add(stringRequest); } RequestQueue defined globally and context assigned in the onCreate() method P.S I rechecked by requesting from the browser and it works. So there are no issues on the Django End. Thanks! -
Processing HTML Quiz Form Through Django/jQuery backend
I have a radio button form that is acting as a multiple choice quiz in my template. I need to check that the answer chosen is the correct answer and then update the score attribute in the model by 1. I know now how to check the button values in jQuery, but I'm not sure how to process it through Djanog. {% extends "mainpage/base.html" %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <title>Multiple Choice</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script> $(document).ready(function(){ $('#quiz').on('change', function(){ if($('input[name=optradio]:checked').val() == "{{correctAnswer}}"){ // var $score = '{{score}}'; // var s = $score.val(); // s++; // alert(s); // alert('youre correct'); //if the user choses the right button and submits quiz, then show them their score } // alert('correct'); }) }) // }) </script> </head> {% csrf_token %} <html> <p>{{ title }}</p> <div class="container"> <form method="GET" class="QuestionForm" id="quiz"> <div class="radio"> <label><input type="radio" name="optradio" id="A" value="{{answerA}}">{{answerA}}</label> </div> <div class="radio"> <label><input type="radio" name="optradio" id="B" value="{{answerB}}">{{answerB}}</label> </div> <div class="radio"> <label><input type="radio" name="optradio" id="C" value="{{answerC}}">{{answerC}}</label> </div> <div class="radio"> <label><input type="radio" name="optradio" id="D" value="{{answerD}}">{{answerD}}</label> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </html> {% endblock %} def results(request): # show results of quiz to user return redirect('https://www.google.de/') def view_takeQuiz(request,quizID): try: quiz … -
Ajax dont show elements
I have little problem. In my Django project I use modal window to create and then update list of objects with Ajax. Below you can see code and two links inside {% if request_user_is_business_analyst %} disappear after update. Why did they become invisible? And how to fix this problem? group_tasks_list.html: {% for group_task in group_tasks %} <tr> <td>{{ group_task.name }}</td> <td> <a class="btn btn-info text-center" href="{{ group_task.get_absolute_url }}">{% trans 'OPEN' %}</a> {% if request_user_is_business_analyst %} <a class="btn btn-warning text-center" href="{{ group_task.get_absolute_url }}"><i class="fa fa-pencil" aria-hidden="true"></i></a> <a class="btn btn-danger text-center" href="{{ group_task.get_absolute_url }}"><i class="fa fa-trash-o" aria-hidden="true"></i></a> {% endif %} </td> </tr> {% empty %} <tr> <td colspan="3" class="table-danger text-center"><i class="fa fa-info-circle" aria-hidden="true"></i> {% trans 'NO DATA' %}</td> </tr> {% endfor %} view.py: def group_task_add(request, project_code): data = dict() project = get_object_or_404(Project, pk=project_code) if request.method == 'POST': form = GroupTaskAddForm(request.POST) if form.is_valid(): group_task = form.save(commit=False) group_task.project = project group_task.save() data['form_is_valid'] = True group_tasks = GroupTask.objects.filter(project=project_code) data['html_group_tasks'] = render_to_string('project/group_tasks_list.html', {'group_tasks': group_tasks}) else: data['form_is_valid'] = False else: form = GroupTaskAddForm() context = {'project': project, 'form': form} data['html_group_task_add_form'] = render_to_string('project/group_task_add.html', context, request=request) return JsonResponse(data) -
How do I use axios in a React project to grab models from Django?
I'm basically just trying to pass a login form from Django to a React component for rendering. I've seen that you can use axios to access django views as an API but I'm still confused about how you would get the login form. Thanks in advance! -
Why am I getting 'str' object has no attribute 'get' on form_valid?
I have looked at other questions regarding this error but can't seem to pinpoint the issue on mine. I know there are better ways to do some of the things I am trying to do in the following code, but right now I'm just trying to pinpoint the culprit causing the following error. Internal Server Error: /users/create/ Traceback (most recent call last): File "/home/ubuntu/workspace/venv_mymanagedservices/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/ubuntu/workspace/venv_mymanagedservices/lib/python3.5/site-packages/django/utils/deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "/home/ubuntu/workspace/venv_mymanagedservices/lib/python3.5/site-packages/django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' [26/Mar/2017 23:02:14] "POST /users/create/ HTTP/1.1" 500 72448 Here's the view where I am trying to create a new user: class CustomerUserCreate(LoginRequiredMixin, CreateView): model = User template_name = 'users/user_create.html' fields = ['username', 'name', 'email', 'password'] # Search for which customer the user is assigned to and deny access if not a customer user or superuser def render_to_response(self, context): customer_admins = Customer.objects.filter(users=self.request.user) if not (customer_admins or self.request.user.is_superuser): return redirect('/403') else: return super(CustomerUserCreate, self).render_to_response(context) def get_form(self, form_class=None): form = super(CustomerUserCreate,self).get_form(form_class) #instantiate using parent customer_admins = Customer.objects.get(users=self.request.user) # Add a field that allows user to select which companies should be added to the Company models' …