Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnicodeDecodeError adding model in Django
When trying to add a model containing unicode in Django 1.9, I get the following error: UnicodeDecodeError at /cleaner/clean/add/ 'utf-8' codec can't decode byte 0x96 in position 209: invalid start byte This occurs in the model class. class Clean(models.Model): name = models.CharField(max_length=100) cv = models.TextField(max_length=10000, blank = True, null = True) cvfile = models.FileField(validators=[validate_file_extension]) #override save method def save(self, *args, **kwargs): get_text = self.cvfile.read() self.cv = get_text self.cv=self.cv.decode("utf-8") super(Clean, self).save(*args, **kwargs) I thought self.cv.decode("utf-8") would solve this as I'm using python 3.6.4, but it does not. Is there a way to solve this? -
Very simple Django form that counts words
I am trying to make a very simple Django form that has 2 options: When you type something in the form, there are 2 buttons: 1 deletes what it has been written, and the other one counts the words with a function I already have. I have been trying to learn from tutorials but all seem too complicated for what this is (which I think, quite easy). This is my html in the env templates python project. <html> <form action="#" method="post"> <label for="your_name">Your name: </label> <input type="text"> <input type="submit" value="Count!" > <input type="submit" value="Reset!"> </form> </html> This is my .py from django import forms class Formu(forms.Forms): nombre=forms.CharField(max_length=100) def count(self, request): #My function to count pass def reset(self, request): # Reset(?) pass I do not really know how to associate the buttons. I think I am missing something to understand, because I do not really know what path should I follow now to associate the buttons "count" and "reset" in the Formu methods "count" and "reset". -
how to refresh template after ajax call
I have a form that contains two select inputs one is for categories and the other for sub categories the form should work like this user should choose an option in the categories and based on that option the sub category options should be updated with new values. but for some reason the sub category options aren't updating template dashboard.html {% block body %} <form> {% csrf_token %} <div class="row"> <div class="input-field col s6 offset-s3"> <select id="list"> <option value="" disabled selected>Choose your Category</option> <option value="education">University/College</option> <option value="hospital">Hospital</option> <option value="business">Business Organizations</option> </select> <label>Categories</label> </div> <div class="input-field col s6 offset-s3"> <select> <option value="" disabled selected>Choose your Category</option> {% for d in data %} <option value="">{{ d.username }}</option> {% endfor %} </select> <label>Sub Categories</label> </div> </div> </form> {% endblock %} {% block script %} <script type="text/javascript"> $('#list').change(function() { $.ajax({ type: 'POST', url: '/dashboard/', data: { category: $('#list').val(), csrfmiddlewaretoken: '{{ csrf_token }}' } }); }); </script> {% endblock %} view.py from django.shortcuts import render, redirect from django.contrib.auth.models import User def dashboard(request): if not request.user.is_authenticated: return redirect('index') else: if request.method == 'POST': category = request.POST['category'] #Here i am using User table because category table is empty data = User.objects.all() print(data) return render(request, 'usecases/dashboard.html', {'data': data}) … -
random ordering with Ajax load more in Django
I'm currently using Ajax to implement load more without refreshing webpages in my Django project. I filtered the queryset to make it in a random order, and with the function get_template_names, it loads additional data every time I hit the load more button. However, as the queryset gets randomized every time the load more button is clicked, the ajax loads each different part of a randomized queryset, so it brings about loading the same data which is overlapped. How can I avoid the overlaps? Is there anyway to keep the only-once-randomized queryset? class StoreListView(ListView): model = Store template_name = 'boutique/index.html' paginate_by = 5 queryset = Store.objects.all().order_by('?') def get_template_names(self): if self.request.is_ajax(): return ['boutique/slider.html'] return ['boutique/index.html'] -
Error at run celery task: Received unregistered task of type
I'm study the celery and want run worker. Open documentation and copied debug_task and make a schedule. Task should run each 20 second. But i get error: Received unregistered task of type 'tasks.debug_task'. What doing wrong? celery from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app', broker='amqp://rabbit:5672') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) app.conf.beat_schedule = { 'ever-10-second': { 'task': 'tasks.debug_task', 'schedule':20.0, } } app.conf.timezone = 'UTC' I start this command: celery -A app worker -B -l info -
How to enroll custom user as students in django
I have a django course model, and custom user profile, with custom user registration form. I need to enroll custom user as students in course model. First step custom user will register, after that from django admin I need to enroll registered user as students in a course. finally, when user or student login I need to show student profile and display the course which student enrolled in that. How to do this ? here is my model code class Course(models.Model): Course_Name = models.CharField(max_length=200) Duration_Time = models.CharField(max_length=50) Course_Fee = models.IntegerField() Discount_Fee = models.IntegerField() Course_Image = models.FileField() Course_Description = models.TextField(max_length=500) def __str__(self): return self.Course_Name + ' - ' + self.Duration_Time class Profile(models.Model): STUDENT = 1 TEACHER = 2 ROLE_CHOICES = ( (STUDENT, 'Student'), (TEACHER, 'Teacher'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=30, blank=False, help_text='Required.') email_confirmed = models.BooleanField(default=False) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) # this method called for admin panel class Meta: verbose_name = 'profile' verbose_name_plural = 'profiles' def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() here is my view code @login_required(login_url='/login/') class StudentCourseListView(generic.ListView): model = Course template_name = 'app/students_profile.html' def get_queryset(self): qs = super(StudentCourseListView, self).get_queryset() return qs.filter(students__in=[self.request.user]) here is my template studentprofile.html {% … -
Jinja2 Compare variable with character
Hello I'm using django templating (jinja) with this template: {% if material.unit =='U' %} p/(u) {% endif %} {% if material.unit == 'M' %} p/(m) {% endif %} I want to print p/(u) when variable material.unit is 'U' and p/(m) when is 'M'. This is not working properly. Is giving me this error: Could not parse the remainder: '=='U'' from '=='U'' -
django runscript No (valid) module for script 'myscriptnamehere.py' found
Python version: 2.7.6 on Ubuntu 14.04. Runscript --version 1.10.4 My scripts worked previously. I'm not sure when they stopped, but now no scripts will run with the command python manage.py runscript myscriptname.py. I've stripped a test script down to print a single line, with no imports and it still errors out. Example script: def run(*args): print "hello" I consistently get the error "No (valid) module for script 'myscripthere.py' found". When I use the -v2 option I can see it check all the various apps and directories and then it fails. If I insert a line I know should throw an error, it throws the error for that line. i.e.: def run(*args): this line is garbage and will thrown an error print "hello" -
django-select2: How does one use dependent_fields to filter possible choices?
forms.py class SoundTestPairForm(forms.Form): sex = forms.MultipleChoiceField( choices=Sound.SEX_CHOICES ) starts_with = forms.MultipleChoiceField( choices=Sound.POS_CHOICES ) user_sound = forms.ModelMultipleChoiceField( queryset=Sound.objects.all(), widget=ModelSelect2MultipleWidget( model=Sound, search_fields=['phrase1__icontains'], attrs={'style': 'width:100%'}, dependent_fields={ 'starts_with':'starts_with', 'sex':'sex', } ) ) What I'd like is for a user to select sex, and select starts_with, and this will filter the possibilities that pop up when said user clicks on the user_sound field. I have also tried this: starts_with = forms.MultipleChoiceField( widget=Select2MultipleWidget( attrs={'style': 'width:75%'}, choices=Sound.POS_CHOICES ), choices=Sound.POS_CHOICES ) ... which is closer to the django-select2 documentation. This still does not work, though. Independent of whether or not a user fill sout sex and starts_with, all of the Sound objects show in the dropdown. Does anyone know how to achieve the desired effect? (This is a follow-up of this question) -
Heroku - deployment of Django application
I have application which is running locally. It is running fine with gunicorn and I am able to start heroku local. My file structure: My Procfile: web: PYTHONPATH=`pwd`/.. gunicorn --bind 0.0.0.0:8000 smartlogisticsserver.wsgi:application Error message from Heroku build on server: App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed Pipefile: [[[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [requires] python_version = "3.6" [packages] "psycopg2-binary" = "*" django-heroku = "*" gunicorn = "*" [dev-packages] and requirements.txt aiohttp==3.2.0 alembic==0.9.9 async-timeout==3.0.0 attrs==18.1.0 awsebcli==3.12.4 blessed==1.14.2 botocore==1.10.12 cement==2.10.12 certifi==2018.4.16 chardet==3.0.4 click==6.7 clients==0.5 colorama==0.3.9 defusedxml==0.5.0 dj-database-url==0.5.0 Django==2.0.5 django-grappelli==2.11.1 django-heroku==0.3.1 dockerpty==0.4.1 docopt==0.6.2 docutils==0.14 Flask==1.0.2 Flask-Admin==1.5.1 Flask-Login==0.4.1 Flask-Migrate==2.1.1 Flask-SQLAlchemy==2.3.2 gunicorn==19.8.1 home==0.3.4 idna==2.6 idna-ssl==1.0.1 itsdangerous==0.24 Jinja2==2.10 jmespath==0.9.3 Mako==1.0.7 MarkupSafe==1.0 multidict==4.2.0 oauthlib==2.0.7 pathspec==0.5.6 psycopg2==2.7.4 psycopg2-binary==2.7.4 PyJWT==1.6.1 pyserial==3.4 python-dateutil==2.7.2 python-editor==1.0.3 python3-openid==3.1.0 pytz==2018.4 PyYAML==3.12 redis==2.10.6 requests==2.18.4 requests-oauthlib==0.8.0 rfxcom==0.5.0 semantic-version==2.5.0 simplejson==3.14.0 six==1.11.0 social-auth-app-django==2.1.0 social-auth-core==1.7.0 SQLAlchemy==1.2.7 tabulate==0.8.2 termcolor==1.1.0 urllib3==1.22 uWSGI==2.0.17 wcwidth==0.1.7 websocket-client==0.47.0 Werkzeug==0.14.1 whitenoise==3.3.1 WTForms==2.1 yarl==1.2.2 Any suggestion what I am doing wrong? Thank you. -
Django form image choice- widget type
Ok. I want to make an app that is changing image from model A and save it as new to model B. On the form in template I want visible images to choose. How can I do it? Model and form A model from django.db import models class Photo(models.Model): photo = models.ImageField(blank=True, null=True) form from django import forms from .models import Photo class Photoform(forms.ModelForm): photo = forms.ImageField(required=True) class Meta: model = Photo fields = ('photo',) Model and form B model from django.db import models class Meme(models.Model): meme = models.ImageField(blank=True, null=True) form from django import forms from Uploader.models import Photo class Memeform(forms.Form): meme = forms.ModelChoiceField(Photo.objects.all(), widget=forms.RadioSelect) class Meta: model = Photo fields = ('meme',) Template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method= "post" enctype="multipart/form-data"> <p> <h2>Your image here</h2> {% csrf_token %} {{ form.as_p }} <button type="submit">Create</button> </p> </form> </body> </html> Now i have widget RadioSelect, but i need to be images visible to choose. -
Adding elements to a form in a view, after the form is filled out
I have a hidden field in my form that would most easily be included in the view. Here's what I have now: if request.method == 'POST': form = Form(request.POST) if form.is_valid(): form.name = name form.save() return HttpResponseRedirect('') There are no errors when I submit the form, and the form elements appear in the DB (so the form works). The element I add (form.name) does not appear in the DB, however. Why doesn't this work, and what can I do about it? -
Pass username to Django form
So i have a custom Form where i need to pass in the request.user.username so i can use that to fill out forms.ModelChoiceField based on what user is accessing it. Here is what i have views.py if request.method == 'POST': form = DepartmentForm(request.POST, username=request.user.username) # Do stuff else: form = DepartmentForm(username=request.user.username) forms.py class DepartmentForm(forms.Form): def __init__(self, *args, **kwargs): self.username = kwargs.pop('username', None) super(DepartmentForm, self).__init__(*args, **kwargs) # Something using self.username But when i try to select fill out self.username, i get a NameError: name 'self' is not defined I tried searching for my solution but none of the one i found seems to work. I would appreciate any help you guys can give. If you need more information, please dont hesitate to ask, and i will update the question accordingly -
Django/Ajax/Jquery running two ajax requests in the same event.
I think I'm really close to getting this working but I need some help with the Jquery as everything works as intended on the second click and beyond. It just doesn't work on the first click. I'm basically trying to replicate the youtube like and dislike buttons. So you click the thumbs up, it shows +1 and if you click it again it subtracts one. All that logic works until I get into the AJAX and Jquery portion. I have one ajax request that adds the user to the "liked" ManyToManyField. Then I have one apiview that I'm connecting to just produce the upvote and downvote count, then displaying that into the template. This all works, but again the first click produces the correct result in the console. The second click produces the "opposite" result in the template and correct result in the console. Then of course if I reload every time I click "up" it works as intended but i'm trying to prevent reloading. template - Jquery/Ajax $(".upvote-btn").click(function(e){ e.preventDefault() var this_ = $(this) var upvoteToggleUrl = this_.attr("data-href") var voteCountAPIUrl = "{% url 'streams:vote-count' streampost.pk %}"; $.ajax({ url: upvoteToggleUrl, method: 'GET', data: {}, success: function(data){ }, error: function(error){ console.log(error) console.log("error") … -
How to pass value from get_queryset() to get_context_data()
As get_queryset() returns only one queryset and I need the length of the queryset search_store to the template file. So, I'm trying to send the value to the template through get_context_data. I know I can get a length of a queryset through {{ queryset|length }}, but for some reason, it only returns a length of queryset separated by pagination, so I only get a partial length. As you see the code, I'm trying to print search_stores.count(), and I need get it in get_context_data from get_queryset. Can anyone let me know how I can do that? class SearchListView(ListView): model = Store template_name = 'boutique/search.html' paginate_by = 2 context_object_name = 'search_stores' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['search_text'] = self.request.GET.get('search_text') context['sorter'] = self.request.GET.get('sorter') if not context['sorter']: context['sorter'] = 'popularity' return context def get_queryset(self): search_text = self.request.GET.get('search_text') sorter = self.request.GET.get('sorter') if not sorter: sorter = 'popularity' if search_text: search_stores = Store.objects.filter(Q(businessName__icontains=search_text) | Q(mKey__icontains=search_text)) if sorter == 'businessName': search_stores = search_stores.order_by(sorter) else: search_stores = search_stores.order_by(sorter).reverse() else: search_stores = '' for store in search_stores: store.mKey = store.mKey.split(' ') print(search_stores.count()) return search_stores -
Attributes from foreignkey in django model
I have this model: class Images(models.Model): relatedproject = models.ForeignKey(Project, on_delete=models.DO_NOTHING) image = models.ImageField(upload_to='static/projects/%s' % relatedproject.name) What I want to accomplish is a filepath for the image to be the same as relatedproject. It can be id or name, that doesn't matter, something like 'static/< relatedproject.name >/imgfilename.jpg'. So that all images are placed in folders relating to its project. However my code here does not work, since Django says ForeignKey has no attributes. Is there a way for me to reference relatedproject when I create my filepath? -
Celery task now working at use a schedule
I created celery task and set a schedule. Task should run each 10 second and writes time in .txt file. But I not see text file with writes time. What doing wrong? celery from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.task.base import periodic_task from datetime import datetime # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app', broker='amqp://rabbit:5672') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task def run(self): open_file = open('text.txt', 'a') time_now = datetime.now() open_file.write(str(time_now) + '\n') open_file.close() app.conf.beat_schedule = { 'ever-10-second': { 'task': 'tasks.run', 'schedule': 10.0, } } app.conf.timezone = 'UTC' I console I see this message: INFO/MainProcess] Scheduler: Sending due task ever-10-second (tasks.run) -
Using Postgres default values with Django ModelForm
I have a ModelForm that inserts into a Postgres DB. The DB has a timestamp that, if not specified, defaults to the current date/time. This is what I want to happen. Since I moved from Django form to ModelForm, the timestamp field is left blank in the DB (I assume Django fills it in as '' when the form is submitted'. How can I use ModelForm, and still have default values applied in Postgres? -
Django rest_framework POST request response like in a GET request
How I mentioned in the title I would like to get a QuerySet back (how it is standard in GET requests, with next and previous url) in a POST request. I have to send a JSON Object to my REST_API with some sensible data and do not want to put them into the URL. I have searched about that a lot but did not found any suitable solution for me... Hope somebody has experience with this or can offer me another better solution. -
django context can't find value which exists when used in template tag
In my view render I return the following context dictionary: company = get_object_or_404(Company, slug=slug) context = { 'company':company, } return render(request, 'company-detail.html', context) I use this in a template tag to check ownership: @register.filter(name='is_owner') def is_owner(user, company): if user.customer.company.id == company.id: return True else: return False I try to see the output of the tag in my template: {{user|is_owner:customer.id}} I get the following error: Internal Server Error: /companies/my-company/ Traceback (most recent call last): File "/django/template/base.py", line 835, in _resolve_lookup current = current[bit] File "/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'customer' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/django/template/base.py", line 841, in _resolve_lookup if isinstance(current, BaseContext) and getattr(type(current), bit): AttributeError: type object 'RequestContext' has no attribute 'customer' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/django/template/base.py", line 849, in _resolve_lookup current = current[int(bit)] ValueError: invalid literal for int() with base 10: 'customer' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, … -
Notification like facebook using ajax in django
I'm new to Django please help me with a notification when a database get updated -
Django Channels and Django Rest Framework integration
I´m trying to build a real-time backend for a multiplayer mobile game with Django. I want to know if someone has worked in a similar project using Django Channels and DRF, or if there has been some progress in the official integration, which I am not able to find. Thanks in advance for any info! -
How to solve django custom user Login error: CSRF verification failed. Request aborted
I have a django custom user login form, When user login the below error shows please help Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. The below Error shows in terminal UserWarning: A {% csrf_token %} was used in a t emplate, but the context did not provide the value. This is usually caused by not using RequestContext. "A {% csrf_token %} was used in a template, but the context " [08/May/2018 23:44:13] "GET /login/ HTTP/1.1" 200 7798 here is my view @csrf_protect def user_login(request): context = RequestContext(request) if request.POST: username = request.POST.get('username') password = request.POST.get('username') user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return render_to_response('app/index.html', context_instance=RequestContext(request)) else: return HttpResponse("You're account is disabled.") else: return render_to_response('app/login.html', context_instance=RequestContext(request)) else: return render_to_response('app/login.html', {}, context) here is my login html code <form class="form-horizontal" name="LoginForm" action="/login/" method="post"> {% csrf_token %} {% if next %} <input type="hidden" name="next" value="{{ next }}" /> {% endif %} -
Django APIClient Post Empty
I am writing a test for a post view. It does work, But when I try and post to it with APIClient.post, I get QueryDict: {}. Here is the test: class SMSCreateData(APITestCase): ... def test_SMS(self): ... postData = {'Body': string, 'From': phNum.phone_number} self.client.post(reverse('SMS-data'), postData) And here is the view: def SMSSubmitDataPointView(request): ... try: print request.POST ... -
Django fixture creation, ignoring relations between objects
I'm testing views in a django app. There are a lot of OneToMany and ManyToMany relations between models (users, departments, reports, etc.) It takes a lot of time upfilling certain fields like name, surname date of birth etc. while creating fixture which I dont use at all. How can I ignore them? Also what are the best practices while creating a fixture? Mine lools like this class TestReportModel(TestCase): allow_database_queries = True @classmethod def setUpTestData(cls): cls.report_id = 99 cls.factory = RequestFactory() cls.user_with_access = User.objects.create(username="user1", password="password") cls.employee = Employee.objects.create(user=cls.user_with_access, fio="name1 surname1", date_of_birth="2012-12-12") cls.indicator = Indicator.objects.create(context_id=10, set_id=10) cls.ife = IndicatorsForEmployees.objects.create(employee=cls.employee, indicator=cls.indicator) cls.report = Report.objects.create(owner=cls.ife) cls.report.id = cls.report_id cls.report.save() cls.user_with_no_access = User.objects.create(username="user_with_no_access", password="password") cls.employee_with_no_access = Employee.objects.create(user=cls.user_with_no_access, fio="name2 surname2", date_of_birth="2018-12-12")