Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save data received by mqtt to databases in Django
Now that I can save received data to databases and connect to mqtt broker when server start, I can't do them together because of the error AppRegistryNotReady("Apps aren't loaded yet.") This is because it will try to load django model while initialize the app. Any advice are appreciate. Thanks in advance. -
Django Mezzanine - Simple custom Admin Form
I need to add job offers section to my company site (as a intro to django for me). The problem is that when i inherit my model from mezzanine's Page model it adds to admins create form all bunch of field which i dont need (like publish dates, draft field, comment field etc). I want to make create/edit job offers form as simple as possible. I tried to inherit it from basic models.Model but it throws an error ... Unknown column 'project_joboffer.id' in 'field list'" I tried to customize Admin Form but im still getting error above. models.py class JobOffer(models.Model): title = models.CharField(max_length=255, null=False, blank=False) place = models.CharField(max_length=255, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) content = models.TextField(blank=False,null=False) published = models.BooleanField(default=True) deleted = models.NullBooleanField() forms.py from django import forms from ckeditor.widgets import CKEditorWidget from models import JobOffer class JobOfferForm(forms.ModelForm): title = forms.CharField(max_length=255, required=True) place = forms.CharField(max_length=255, required=False) content = forms.CharField(required=True , widget=CKEditorWidget()) published = forms.BooleanField(initial=True) deleted = forms.NullBooleanField() # class Meta: # model = JobOffer admin.py class JobOfferAdmin(admin.ModelAdmin): form = JobOfferForm admin.site.register(JobOffer, JobOfferAdmin) -
Raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
I have google this question . there plenty of similar problems , but i can't find proper answer. This is details of error Log : Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "d:\django\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "d:\django\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "d:\django\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "d:\django\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "d:\django\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "d:\django\django\db\migrations\executor.py", line 91, in migrate self.recorder.ensure_schema() File "d:\django\django\db\migrations\recorder.py", line 57, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NOT NULL)' at line 1")) This is settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': '*****', 'PASSWORD': '****', 'HOST': '**.***.***.**', 'PORT': '3306', } } This is my models.py from django.db import models class Test(models.Model): _name = models.CharField(max_length=20, default="aaa") _score = models.CharField(max_length=20, default="DDD") Mysql version : mysql Ver 14.14 Distrib 5.5.53, for linux2.6 (x86_64) using readline 5.1 Who has ideas for this problem , Thanks … -
Use multiple block and views in django templates
I am new to django, and I see that you could create templates that you could populate in views. You could also create some basic.htm that everyone extends... Let say I have two pages: (django demo) List of all questions Detail of the question. Now I would like to create "one page" that have first view as sidebar and another as a "detail- right" view. I would like that on clicking on the list in sidebar change right vies. It would be nice, if I could use different views (inside views.py) for loading separate templates. I wish for base html would be something like this : <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Makro Zadravec</title> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'demo/css/bootstrap.min.css.css' %}" /> </head> <body class="body" style="background-color: #f6f6f6"> <div> <h1> This is title</h1> </div> <div> {% block sidebar %} {% endblock %} </div> <div> {% block content %} {% endblock %} </div> </body> </html> And then I would have template for blocks: content sidebar in separate views. -
django image upload cannot import name _imaging
uploading image in DJANGO web app hosted in azure is not working it is showing me an error error cannot import name _imaging but it works fine in local machine.i tried installing different version of pillow but it still displaying the error -
Unable to sync dropbox and googledrive account, I get following error
asset = Asset.objects(remote__id=entry_id, remote__source='dropbox', org=user.org).first() Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3/dist-packages/mongoengine/queryset/manager.py", line 37, in get queryset = queryset_class(owner, owner._get_collection()) File "/usr/lib/python3/dist-packages/mongoengine/document.py", line 209, in _get_collection cls.ensure_indexes() File "/usr/lib/python3/dist-packages/mongoengine/document.py", line 765, in ensure_indexes collection.create_index(fields, background=background, **opts) File "/usr/local/lib/python3.5/dist-packages/pymongo/collection.py", line 1571, in create_index self.__create_index(keys, kwargs) File "/usr/local/lib/python3.5/dist-packages/pymongo/collection.py", line 1472, in __create_index parse_write_concern_error=True) File "/usr/local/lib/python3.5/dist-packages/pymongo/collection.py", line 232, in _command collation=collation) File "/usr/local/lib/python3.5/dist-packages/pymongo/pool.py", line 471, in command collation=collation) File "/usr/local/lib/python3.5/dist-packages/pymongo/network.py", line 116, in command parse_write_concern_error=parse_write_concern_error) File "/usr/local/lib/python3.5/dist-packages/pymongo/helpers.py", line 210, in _check_command_response raise OperationFailure(msg % errmsg, code, response) pymongo.errors.OperationFailure: only one text index per collection allowed, found existing text index "name_text_description_text_content_text_tag_content_text" -
getting error while running "sudo supervisorctl reread"?
I am trying to deploy a Django application with gunicorn and nginx with supervisor. I am referring the following link : referral link While running the following command : sudo supervisorctl reread Getting error : error: <class 'socket.error'>, [Errno 2] No such file or directory: file: /usr/lib/python2.7/socket.py line: 228 Please help to resolve ! -
how to get data of a specific user from a django model and store each field in a separate variable
I have a model named Credit with 16 fields. I want to fetch data of a specific user using primary key and store value of each field in the separate variable because i have to perform some mathematical operation on these data. These data are required to be passed to a python script. How can i get this done? -
how to redirect? mapping? url in django
i have poll app following is my root urls urlpatterns = [ path('poll/', include('myproject.poll.urls')), ] and I have app url router = DefaultRouter() router.register(r'', PollViewSet) urlpatterns = [ path('', include(router.urls)) ] i used ViewSet so I can use reverse('poll-list'), reverse('poll-detail')... and i can access "xxx.xxx.xxx.xxx/poll" and "xxx.xxx.xxx.xxx/poll/1/" .... but I want to redirect(mapping?) url when i access "xxx.xxx.xxx.xxx/api/v1/poll/" to "xxx.xxx.xxx.xxx/poll" I don't want to change existing urls. because I want to bundle the views of several apps into one api url file. How can i do that? and what is the best way? -
TypeError: expected string or bytes-like object on
I have the following code: for match in tag_re.finditer(self.template_string): start, end = match.span() which is generating the following error: ... File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/template/base.py", line 191, in compile_nodelist tokens = lexer.tokenize() File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/template/base.py", line 399, in tokenize for match in tag_re.finditer(self.template_string): TypeError: expected string or bytes-like object Curious about this error, I added: print(type(self.template_string)) for match in tag_re.finditer(self.template_string): This is the result: <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'django.utils.functional.lazy.<locals>.__proxy__'> Internal Server Error: /workflow/archive/ Traceback (most recent call last): ... tokens = lexer.tokenize() File "/Users/vng/.virtualenvs/prometheus/lib/python3.6/site-packages/django/template/base.py", line 399, in tokenize for match in tag_re.finditer(self.template_string): TypeError: expected string or bytes-like object <class 'str'> Then I tried to do a patch: self.template_string = str(self.template_string) for match in tag_re.finditer(self.template_string): And the error is gone. Why isn't django.utils.functional.lazy.<locals>.__proxy__' evaluated to be a string at that particular point in time? -
Multiple users log on
I have a use case in my web application: Foo logs on and the information about him appears on the page(name, profile picture) and then Tuxy logs on and the information about him appears on the page too. Now is the strange thing, if Foo refreshes his page Tuxy's information will appear on page. Can anyone tell me what could be the cause of this problem? It seems that somehow all accounts are overwritten by the last user that logs on. I do not know what information I am missing, please help. -
Mongodb or Mysql which one is good for storing image links and keywords
I am working on a django project which shows images the db will have image links and descriptions(keywords) i dont want duplicate entries in the imagelink which is the best database to use with it? shall i go with mysql to avoid duplicate entries? but i realy like the json structure of mongodb it is easy to handle i think Please suggest a good one -
Can i make a doc or excel file password protected by python ?
I am developing a website where a user can download/i will send them (some other way) some pdf, doc or excel file. I should confirm that the documents are password protected and the password is sent to the user via mail. I use PyPDF2 for pdf files. But how can i do the same thing for doc and excel files. import PyPDF2 output = PyPDF2.PdfFileWriter() file1 = open("1.pdf", 'rb') reader1 = PyPDF2.PdfFileReader(file1) for pages in range(reader1.numPages): output.addPage(reader1.getPage(pages)) output.encrypt('hello') output_file = open('encrypted_output.pdf', 'wb') output.write(output_file) output_file.close() file1.close() -
django-allauth doesn't register social links
Something wrong happened to django-allauth when I deployed my site on hosting. I didn't do any to django-allauth. Look, what I get on localhost: django-allauth on localhost and on hosting: django-allauth on hosting Why that's happening? -
Django Forms: How to avoid hidden input, without changing URL
I have run into a problem that I cannot completely wrap my head around. I have a model Question that among other things contains a statement, information about the user that asked it, as well as information on amount of yes-votes and no-votes. In a template, I have a situation similar to the following one: {% for question in list_passed_with_questions %} <p>{% question.statement %}</p> <form method="post"> {% csrf_token %} {{ vote_form.as_p }} #vote_form makes the user choose between 'yes'/'no' <button type="primary">Think</button> </form> {% endfor %} My objective is to be able to know which question each user votes for. Suppose I have a list of questions in my template, each one with a form that allows a user to vote - then how could I know which one the user voted for when using their input in views.py? Regardless of whether the vote_form is a Form or ModelForm instance, request.POST will only contain information about the user's yes/no-choice (that is, it will not contain for example the pk of question). One way to solve this would be to have the submit button lead to a new url, and pass the pk of the question answered as a slug. Another way … -
call js function from .py file
I am new to django. I have a special situation in which I need to call a js function after running some python code in my views.py file. Is there any way doing that? tnx -
Some dates in Bootstrap Datetimepicker are incorrectly gray-ed out
Some dates in Bootstrap Datetimepicker are incorrectly gray-ed out in chrome 65, Please find the attached screenshots -
How to make Required: boolean field in model Django
I have a model with a field called in is_student and is_teacher Student and Teacher forms is_teacher = models.BooleanField('teacher status', default=False) is_student = models.BooleanField('student status', default=False) I want to make sure this field is: Always Checked by the user True *Required Currently: is_teacher in TeacherApplications Model When unchecked - it saved 0 to the form and continues. (Not good) When checked gives me this error: ValueError at /register/teacher invalid literal for int() with base 10: '' Currently: is_student in StudentProfile Model When checked gives this error ValidationError at /register/ ["'on' value must be either True or False."] When unchecked it saved 0 to the form and continues. (Again, not good) model class StudentProfile(models.Model): user = models.OneToOneField('Accounts', related_name='student_profile') # additional fields for students AMEB_Ratings = models.PositiveIntegerField(default=0) is_student = models.BooleanField('student status', default=False) class TeacherApplications(models.Model): user = models.OneToOneField('Accounts', related_name='teacher_profile') # additional fields for teachers instrument = models.TextField(max_length=500, blank=True) skill = models.CharField(max_length=30, blank=True) experience_in_years = models.PositiveIntegerField(blank=True) is_teacher = models.BooleanField('teacher status', default=False) view def teacherApplication(request): # Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register if request.method == "POST": user_form = UserForm(request.POST) form … -
Add StreamingHttpResponse into middle of Django template
Python 3.6.3, Django 2.0.3 I'm new to django, but I'm trying to make a pretty simple site where someone can trigger a few tasks that were previously just misc, stand-alone python scripts. Unfortunately those tasks can take a pretty long time. I want to be able to display the output from those tasks in the middle of the following template (where {{ stream }} is) so the user has some meaningful feedback. {% load pagePieces %} {% page_header %} <div class="container"> <div class="row"> <a class="btn" href="/"><i class="fa fa-chevron-left"></i> Home</a> </div> <div class="row row-header"><h1>{{ operation }}</h1></div> <div class="row row-content"> {{ stream }} </div> </div> {% page_footer %} In my view file I've tried a few different things, but here's about where I'm at now (this is somewhat simplified. I took out some error handling and changed some names): def myaction(request): output_template = loader.get_template('myapp/process_output.html') return StreamingHttpResponse( output_template.render({ 'operation': 'That long running task', "stream": streaming_wrapper() }) ) def streaming_wrapper(): output_template = loader.get_template('myapp/process_output.html') x = yield from a_module.long_running_task() yield output_template.render({ 'operation': 'That long running task', "stream": x }) This does stream the output from long_running_task(), but doesn't load the rest of the template until after it's done. At other points, I've gotten the output … -
Test case for Django ModelForm with ModelChoiceField
I'm trying to write a simple test case to test a Django form that permits the assignment of an Orange object to an Apple object. forms.py class AppleOrangeAssignmentForm(forms.ModelForm): orange = forms.ModelChoiceField(required=True, \ queryset=Orange.objects.filter(apple=None)) class Meta: model = Apple fields = ('orange') The queryset on orange is there to ensure that the values in the dropdown are only Oranges that aren't already assigned to other Apples. This code works correctly and consistently in the view that calls it. In the test case below, I am create a brand new Orange to ensure that I have one that it is not assigned anywhere else. test.py def test_apple_orange_assignment(self): apple = Apple.objects.get(pk=1) self.assertEquals(apple.orange, None) orange = Orange.objects.create(name='clementime') form_data = { 'orange': orange } form = AppleOrangeAssignmentForm(data=form_data, instance=apple) self.assertTrue(form.is_valid()) # <=== Fails here Weirdly, the form does not validate in the test case! form.errors says: form.errors = {'orange': ['Select a valid choice. That choice is not one of the available choices.']}. When I dig in further, I can see that the orange I am trying to assign does appear in form.fields['orange'].queryset, though. I have tried everything to try to get this to validate. I have tried changing the queryset in the form field to Orange.objects.all(). … -
Django: filtering queryset by "parameter has part of field's value"?
I have a simple model: class Place(models.Model): name = models.CharField() and it has some representative names like Starbucks, McDonald's, etc. And I also have some place names as parameter, for example: Starbucks Pike Place McDonald's Sand Lake Road Another Starbucks Out There What I'm trying to achieve is to filter/get appropriate Place object with given parameters, determine whether it has part of place's name. How can I do this with django's QuerySet API? Have checked references and forum for something like below but was no luck: Place.objects.get(name__ispartof=PARAM) # or Place.objects.get(PARAM__contains=Q('name')) In Postgres, my case may equivalent to: SELECT id FROM table WHERE 'Starbucks Pike Place' LIKE CONCAT('%', name, '%') Should I have to perform a raw() SQL query for this? Thanks in advance. -
Page not found (404) Error on Django:
the output we are looking at is to get title on page http://127.0.0.1:8000/courses/1/1/ and for further pages /2/ or /3/ courses/views.py from django.shortcuts import get_object_or_404, render from .models import Course, Step def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html', {'courses': courses}) def course_detail(request, pk): course = get_object_or_404(Course, pk=pk) return render(request, 'courses/course_detail.html', {'course': course}) def step_detail(request, course_pk, step_pk): step = get_object_or_404(Step, course_id=course_pk, pk=step_pk) return render(request, 'courses/step_detail.html', {'step': step}) our focus will be : def step_detail(request, course_pk, step_pk): step = get_object_or_404(Step, course_id=course_pk, pk=step_pk) return render(request, 'courses/step_detail.html', {'step': step}) step_detail.html {% extends "layout.html" %} {% block title %} {{ step.title }} - {{ step.course.title }}{% endblock %} {% block content %} <article> <h2> {{step.course.title }} </h2> <h3> {{step.title }} </h3> {{ step.content|linebreaks }} </article> {% endblock %} course/url.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.course_list), url(r'(?P<course_pk>\d+)/(?P<step_pk>\d+)/$', views.step_detail), url(r'(?P<pk>\d+)/$', views.course_detail), ] -
Who set the Transfer-Encoding: chunked header?
I am using Django, mod_wsgi and Apache. When I make a response as StreamingHttpResponse and return, Transfer-Encoding: chunked header is set in the response. But when I add the Content-Length header to the resposne, Transfer-Encoding header is removed and only the Content-Length header exists. Who set and remove the Transfer-Encoding header? -
Register Form not saving to database: Django no error?
Weird issue with by registration form, not sure i am doing wrong. I have StudentProfile Model, that I am trying to save data from StudentResistrationForm but the data is not being saved into database - no errors! Is the view logic correct? What am I missing? Ideas please model class Accounts(AbstractUser): email = models.EmailField('email address', unique=True) first_name = models.CharField('first name', max_length=30, blank=True) last_name = models.CharField('last name', max_length=30, blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) # asdd bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) class StudentProfile(models.Model): user = models.OneToOneField('Accounts', related_name='student_profile') # additional fields for students AMEB_Ratings = models.PositiveIntegerField(default=0) is_student = models.BooleanField('student status', default=False) form class StudentResistrationForm(forms.ModelForm): class Meta: model = StudentProfile fields = ( 'AMEB_Ratings', ) def save(self, commit=True): user = super(StudentResistrationForm, self).save(commit=False) # user.first_name = self.cleaned_data['first_name'] # user.last_name = self.cleaned_data['last_name'] user.AMEB_Ratings = self.cleaned_data['AMEB_Ratings'] if commit: user.save() return user class UserForm(forms.ModelForm): class Meta: model = get_user_model() fields = ('username', 'email', 'password') view def registerStudent(request): # Once register page loads, either it will send to the server POST data (if the form is submitted), else if it don't send post data create a user form to register if request.method == "POST": user_form = UserForm(request.POST) form = StudentResistrationForm(request.POST) if … -
Getting celery group results from group id
I am developing a django application with celery 4.0. How can I use the celery group id job_results to retrive result from each member task while job is in progress? # In a view job = group([sub1.s(), sub2.s(), sub3.s()]) job_results = job.apply_async() request.session['my_task_id'] = job_results.id print(job_results.completed_count()) # prints count #In another view (this part fails) my_task_id = request.session.get('my_task_id') regenerated_job_results = GroupResult(seocheck_task_id, app=app) print(regenerated_job_results.completed_count()) # Gives error This is the error I get. Traceback (most recent call last): File "~/proj/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "~/proj/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "~/proj/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "~/proj/seocheck/views.py", line 52, in ajax_seocheck_results print(regenerated_job_results.completed_count()) File "~/proj/venv/lib/python3.6/site-packages/celery/result.py", line 565, in completed_count return sum(int(result.successful()) for result in self.results) TypeError: 'NoneType' object is not iterable I just need to convert the group id str to 'GroupResult' instance again. My celery backend is 'django-db' CELERY_RESULT_BACKEND = 'django-db'