Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: lowest class based view or mixin with request attribute
What's the minimum class based view or mixin I can inherit from to have access to Django request object via the request attribute in my view? -
Only last label input value being returned in Django
I am pretty new in Django and I guess there is something I am overlooking. I have a form that I am populating dynamically as shown below <form method="post"> {% csrf_token %} {{ profile.days }}//Only prints last radio button value {% for period, value in profile.periods.items %} <h2>{{ period }} Reports</h2> <label> <input name="days" value={{ value }} type="hidden"> <input name="reports_allowed" type="radio" {% if profile.reports_allowed and profile.days == value %} checked {% endif %}> Each {{ value }} send me a summary of my checks </label> {% endfor %} <button name="update_reports_allowed" type="submit" class="btn btn-default pull-right">Save</button> </form> I want to be able to access the value of the selected radio button which I am doing as follows form = ReportSettingsForm(request.POST) if form.is_valid(): print(form.cleaned_data) days = form.cleaned_data["days"] print(days)# Prints only the last value always Any help on how to get value of radio button clicked will be highly appleciated. -
Modified Django admin clean() method not being invoked
I have developed a tool (to be used internally) based on the Django admin site. I have model validators in place which work brilliantly, but to do more complex validations, I am attempting to overwrite the clean() method in admin.py My admin.py looks like this: from django.contrib import admin from .models import Provider, Employer, Person, Learnership, Qualification, Unit_Standard from django import forms class ProviderForm(forms.ModelForm): class Meta: model = Provider fields = 'all' def clean(self): provider_start_date = self.cleaned_data.get('provider_start_date') provider_end_date = self.cleaned_data.get('provider_end_date') if provider_start_date > provider_end_date: raise forms.ValidationError("Start date can't be after end date") return self.cleaned_data admin.site.register(Provider) The models.py for the Provider Model: class Provider(models.Model): ... lots of stuff here ... provider_start_date = models.DateField() provider_end_date = models.DateField(blank=True, null=True) ... lots of stuff here ... def __str__(self): return '%s %s' % (self.provider_name, self.provider_code) The problem is that the code displayed in the admin.py doesn't seem to fire, and you can save the record with the end date before the start date. The Django admin interface is really an amazing feature of the framework, and I think that other people have probably also run into this problem of more advanced validations not being possible, so it would help them as well. -
django 1.11 - OperationalError no such column
I have tried to py manage.py makemigrations and then py manage.py migrate but when I add a new field to my model, this error occurs. I also have tried deleting all the migrations and doing the makemigrations and migrate things again but it still does not solve the problem. Basically I have a model Schedule and I added a Customer field in it which the relationship is customer = models.ForeignKey(Customer) EDIT: Here is my model class Schedule(models.Model): name = models.CharField(max_length=250) deadline_date = models.DateField() is_completed = models.BooleanField(default=False) description = models.CharField(max_length=1000, default="") customer = models.ForeignKey(Customer) Here is the traceback: Traceback: File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\db\backends\utils.py" in execute 65. return self.cursor.execute(sql, params) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\db\backends\sqlite3\base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (no such column: schedule_schedule.customer_id) was the direct cause of the following exception: File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\contrib\admin\options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\utils\decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.4-py3.6.egg\django\views\decorators\cache.py" in _wrapped_view_func 57. response = view_func(request, *args, … -
Django context processor to show images
I want show a random images in my webpage, then I made a context processor of this way (previously added in my context_processors settings ...): # -*- coding: utf-8 -*- from random import choice images_people = ['https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia2.jpg','2', 'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia3.jpg', 'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia4.jpg', 'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/bolivia-children.jpg', 'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/ElZocalo.jpg', 'https://s3-sa-east-1.amazonaws.com/ihost-project/assets/img/israel.jpg', ] def images(request): return {'images': choice(images_people)} In my template I am invoking this context_processor of this way: <div class="portrait"> <div class="img-cont" style="background: url('{{ images }}') no-repeat center; background-size:cover;"> </div> # Add caption to image <!-- <span></span> --> </div> How to can add caption to each image in my images_people list? This context_processor can be improved in the level practices sense? -
CSRF token missing or incorrect, 404
This is a widely asked question, but most of them have a different scenario, and I believe mine too. Below are my project details apps.ulrs.py: urlpatterns = [ url(r'^index/$', views.IndexView, name='index'), url(r'^signup/$', views.signupview, name='sign_up'), ] models.py: from django.db import models from django.core.urlresolvers import reverse #from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Registration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length = 250) password = models.CharField(max_length = 250) email = models.CharField(max_length = 250) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Registration.objects.create(user=instance) instance.registration.save() views.py: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm from .forms import SignUpForm #from django.corecontext_processors import csrf from django.template import RequestContext from django.shortcuts import render_to_response from django.views import generic class IndexView(generic.View): templet_name = 'user_info/index.html' def signupview(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('registration_form.html') else: form = SignUpForm() #return render(request,'user_info/registration_form.html', {'form': form}) return render_to_response('user_info/registration_form.html', {'form': form, }, context_instance = RequestContext(request)) I doing some research I came to know that we need to import "csrf" in my views.py , so I tried below: #from django.corecontext_processors import csrf … -
Adding a file through Django shell
Django 1.11.6 I am trying to save a file through Django shell. Could you have a look at the traceback and tell me what I do wrongly? Model: class ItemFile(ChecksumMixin, models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT, verbose_name=_("item")) file = models.FileField(blank=False, max_length=255, upload_to=get_item_path, verbose_name=_("file")) In the shell: from django.core.files import File f = File('/home/michael/PycharmProjects/photoarchive_4/general/static/test/text_1.pdf', 'rb') i = Item.objects.get(pk=1) ItemFile.objects.create(item=i, file=f) Traceback: Traceback (most recent call last): File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1059, in <listcomp> for obj in self.query.objs File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1058, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1008, in pre_save_val return field.pre_save(obj, add=True) File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/db/models/fields/files.py", line 296, in pre_save file.save(file.name, file.file, save=False) File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/db/models/fields/files.py", line 94, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/core/files/storage.py", line 54, in save return self._save(name, content) File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/core/files/storage.py", line 351, in _save for chunk in content.chunks(): File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/core/files/base.py", line 81, in chunks data = self.read(chunk_size) File "/home/michael/PycharmProjects/venv/photoarchive_4/lib/python3.6/site-packages/django/core/files/utils.py", line 16, in <lambda> read = property(lambda self: self.file.read) AttributeError: 'str' object has no attribute 'read' -
Range of dates in a django model and admin
How to register a range of dates in the model and have in admin a widget similar to this? Exemple to widget It's possible to use DateTimeField or calendar? -
Cannot connect to Heroku through cmd line
I have a Django project that I have deployed on a heroku web server and use PyCharm as my IDE. I used to be able to interact with my web server with "heroku run bash", however, now when I try running "heroku run bash" I get: ▸ stat /.local/share/heroku/client/bin/heroku: not a directory ▸ fork/exec /.local/share/heroku/client/bin/heroku: not a directory I'm not sure what has changed, but I can't seem to connect to my heroku webserver anymore. I can still push changes using git push heroku master, but any other interaction with my heroku server doesn't seem to work anymore. I've already checked with Heroku and their systems are running just fine. How do I reconnect to my heroku web server again with PyCharm? Or just in general? Thanks in advance for your help! -
Docker-compose + Heroku + Django + Gunicorn
I am getting an H14 Heroku error when trying to deploy my built docker image to heroku. Since the Heroku documentation says a CMD command is required and it appears that the commands in the Procfile are not actually run I am at a bit of a loss as to what to do. My heroku error log : ` 2017-11-01T11:19:47.714787+00:00 app[globus.1]: Post-processed 'admin/css/forms.css' as 'admin/css/forms.2003a066ae02.css' 2017-11-01T11:19:47.715387+00:00 app[globus.1]: 2017-11-01T11:19:47.715389+00:00 app[globus.1]: 0 static files copied to '/globus/staticfiles', 62 unmodified, 24 post-processed. 2017-11-01T11:20:48.337975+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=kolland-globus-1.herokuapp.com request_id=e2a6eda9-e2bf-477b-9987-b5995d110b0e fwd="2.87.181.37" dyno= connect= service= status=503 bytes= protocol=https 2017-11-01T11:20:48.683132+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=kolland-globus-1.herokuapp.com request_id=eb2e00ee-826a-4ddd-aa22-78e242612e8f fwd="2.87.181.37" dyno= connect= service= status=503 bytes= protocol=https 2017-11-01T11:20:48.766644+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=kolland-globus-1.herokuapp.com request_id=60d645a6-8657-4236-80d9-7a8f8e880640 fwd="2.87.181.37" dyno= connect= service= status=503 bytes= protocol=https Output of heroku ps: === globus (Free): /start.sh (1) globus.1: up 2017/11/01 13:19:44 +0200 (~ 17m ago) Heroku Control Panel for the app says: globus /start.sh My code is as follows: 1) The start.sh script: #!/bin/bash python manage.py migrate # Apply database migrations python manage.py collectstatic --clear --noinput # clearstatic files python manage.py collectstatic --noinput # collect static files # Prepare log files and … -
UnicodeDecodeError in celery task being run by Supervisor
We received the following error from our staging setup running celery via Supervisor Sender: <@task: custom_plugins.tasks.cleanup_unused_media_task of test_app_directory:0x7fc87c5b1a90 (v2 compatible)> args: [] kwargs: {} <type 'exceptions.UnicodeDecodeError'> 'ascii' codec can't decode byte 0xc3 in position 39: ordinal not in range(128) File "/home/app_runner/.virtualenvs/TestApplication/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/home/app_runner/.virtualenvs/TestApplication/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/opt/webapps/TestApplication/test_app_directory/custom_plugins/tasks.py", line 11, in cleanup_unused_media_task interactive=False, File "/home/app_runner/.virtualenvs/TestApplication/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 115, in call_command return klass.execute(*args, **defaults) File "/home/app_runner/.virtualenvs/TestApplication/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/opt/webapps/TestApplication/test_app_directory/custom_plugins/management/commands/cleanup_unused_media.py", line 47, in handle unused_media = get_unused_media(exclude=exclude, include=include) File "/opt/webapps/TestApplication/test_app_directory/custom_plugins/cleanup.py", line 92, in get_unused_media all_media = _get_all_media(exclude=exclude, include=include) File "/opt/webapps/TestApplication/test_app_directory/custom_plugins/cleanup.py", line 64, in _get_all_media for root, dirs, files in os.walk(six.text_type(settings.MEDIA_ROOT)): File "/home/app_runner/.virtualenvs/TestApplication/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/home/app_runner/.virtualenvs/TestApplication/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/home/app_runner/.virtualenvs/TestApplication/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/home/app_runner/.virtualenvs/TestApplication/lib/python2.7/os.py", line 294, in walk for x in walk(new_path, topdown, onerror, followlinks): File "/home/app_runner/.virtualenvs/TestApplication/lib/python2.7/os.py", line 284, in walk if isdir(join(top, name)): File "/home/app_runner/.virtualenvs/TestApplication/lib/python2.7/posixpath.py", line 80, in join path += '/' + b I have a file with non ascii characters in one … -
project's Interpreter version is 3.5 still get the SyntaxError: Non-ASCII character Error
When I execute the migrations: python manage.py makemigrations I get the bellow error: SyntaxError: Non-ASCII character '\xe4' in file /Users/abx/Desktop/website/website/settings.py on line 40, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details But my Django project's Interpreter version is 3.5.2 in my PyCharm. -
Django LoginView send success message
I have one LoginView Class. Here: class LoginFormView(LoginView): template_name = 'auth/login.html' success_url = '/profile' messages.success('<p class="success_login">You were successfully login</p>') And here: def log_out(request): logout(request) messages.success(request, '<p>You were successfully logout</p>') return redirect('/') Through my function i can send success message as messages.success but when.. Log in message success requires *request *message i can not request. What to do? Any ideas? Error is : messages.success('<p class="success_login">You were successfully logout</p>') TypeError: success() missing 1 required positional argument: 'message' Thank you in advance -
How to propagate parent attributes in Django models?
Is there a way to propagate child attributes in parent class without having to access it by its related name? Please consider the following example: class BaseA(models.Model): pass class BaseB(models.Model): a = models.ForeignKey('BaseA') class A(BaseA): base = models.OneToOneField('BaseA', related_name='related') field = models.IntegerField(default=0) def some_method(self): pass class B(BaseB): base = models.OneToOneField('BaseB') # code in view model_b = B() model_b.a.some_method() I cannot access the some_method method because model_b.a returns a BaseA() instance instead of A(), if I want to access this method I have to: model_b.a.related.some_method() # or model_b.a.related.field Is there a way to propagate the properties and methods from the base class so I won't have to access using the related name? -
Custom location for custom Django commands
In my Django project I have multiple apps and would like to add custom Command which is general (populate_db) to all apps. However, Django seems to be registering custom commands only from the INSTALLED_APPS locations (i.e. you must place management folder within a folder of an app). Is there a way to place management folder in project_folder. Here is the desired dir structure: . ├── __init__.py ├── app_1 | ├── admin.py | └── ... ├── app_2 | ├── admin.py | └── ... ├── project_folder | ├── settings.py | └── management | ├── __init__.py | └── commands | ├── __init__.py | └── populate_db.py └── manage.py -
How to save a repositionned image (new position after dragging) with django?
I have a cover profile image in my web application and I want to reposition the image like facebook style cover page reposition. I have found a usefull example (you can find it in this link using Jquery and PHP) Dragging the image is done correctly but the problem when I save the picture after repositioning it , it's not saved as I want. This is my code : HTML <form action="{% url 'save_profile_cover' %}" role="form" method="post" enctype="multipart/form-data"> <div class="cover overlay cover-image-full height-300-lg cover-resize-wrapper" style="margin-top:-15px;height: 300px;"> <img src="{{ request.user.get_cover_picture }}" alt="cover" id="image" style="position: relative"/> <div class="drag-div" align="center" id="button_block" style="display: none">Drag to reposition</div> <div class="overlay overlay-full"> <div class="v-top btn-group" style="margin-top:15px;" id="plus_button"> <button type="button" class="btn btn-cover dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <i class="fa fa-pencil"></i> </button> {% csrf_token %} <div hidden> {{ form.profile_cover }} </div> <ul class="dropdown-menu pull-left" id="cover_options"> <li><a href='#' onclick="repositionCover();">Reposition...</a></li> <li><a href="#" id="upfile" onclick="repositionCover();">Upload Photo...</a></li> </ul> </div> </div> <div class="v-center overlay" style="display: none" id="buttons_block"> <button class="btn btn-success pull-left" type="submit" id="save_button" style="margin-right: 10px ;margin-top: 10px"><i class="fa fa-save"></i> Save </button> <a href="{% url 'upcoming_events_list' %}" type="button" class="btn btn-default pull-left" id="cancel_button" style="margin-top: 10px" ><i class="fa fa-remove"></i> Cancel </a></div> </div> </form> <script src="{% static "profile/js/change_cover.js" %}"></script> <script> $("input[name='profilecover']").addClass("cover-position"); function repositionCover() { $('.cover-wrapper').hide(); $('.screen-width').val($('.overlay-full').width()); console.log($('input.cover-position').length) $('.cover-image-full img') .css('cursor', … -
how to use forloop.counter in in another django template?
I want to print all the Questions and their respective answers. I have passed the list of all the Questions and a list of all the answers of all the questions. I am doing something like this in my html {% for question in questions %} <div class="row"><h5>Q.{{forloop.counter}} </h5>&nbsp; {{question.0}}</div> {% for answer in answers.0.getanswers %} <blockquote> <div class="row"><h6>A.{{answer}} </h5> {{answer}}</div> <footer> </footer> </blockquote> {% endfor %} <form method="POST" class="form-group"> {% csrf_token %} answer: <input type="text" name="answer_text" class="form-control" placeholder="Write"> <br> <input type="hidden" name="rating1" value="2"> <input type="hidden" name="question_id" value="{{question.1}}"> <input type="submit" class="btn btn-primary" value="answer" class="form-control"> </form> <br> {% endfor %} and in my views.py ihave something like this class Question_answer(): question_id=-1 answers = [] def getanswers(self): return self.answers def detail(request,ID): #something cursor.execute("""Select * from Question where product_id='""" + str(ID) + "';") questions = cursor.fetchall() ids = [] for question in questions: ids.append(question[1]) answers = [] for i in ids: cursor.execute("Select * from Answer where question_id='" + str(i) + "';") temp = list(cursor.fetchall()) b = Question_answer() b.question_id = i b.answers = temp answers.append(b) return render(request, 'html',{'questions': questions, 'answers': answers}) But it seems like answers.forloop.counter is not giving me answers.0,answers.1... but when i replace answers.forloop.counter0.getanswers with answers.0.getanswers, it does print all the answers … -
User not recognised in django-rest-framework-social-oauth2.
When registering my application I enter my superuser name in user field but it throws error stating invalid. -
Show a paginated ListView and an UpdateView on the same template page
I am trying to create a Django page where one part of a model can be updated and another part is shown in a table. The model looks like this: class Cost(models.Model): name = models.CharField(max_length=200) amount = models.DecimalField(max_digits=50, decimal_places=2) description = models.CharField(max_length=200) I previously had it working by just having an UpdateView for the form and the table included in the form template. Now though, as I want to include pagination on the table, I need to use two views on the same page. The page I have designed should look something like this in the end: I am not worried about the styling at the moment my main focus at the moment is getting the form and the table on the same page. In its current state the only thing that I don't have is the pagination for the table: Template: {% extends 'pages/dashboard.html' %} {% load i18n humanize crispy_forms_tags %} {% block content %} <div> <h1 class="text-center">Cost: {{ cost.name }}</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Edit cost data / feed: {{ cost.name }}</h3> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary pull-right ml-1" type="submit">{% trans "Update" %}</button> <a class="btn btn-secondary pull-right" href="{{ … -
Django 1.6 to 1.11 Admin.py migration
I am trying to port an old Django 1.6 admin.py code into Django 1.11 and for whatever reason, it is not working on 1.11. I am sending you the code below so some of you might give me some points on areas of the old code that will probably not work on Django 1.11. Thanks in advance for any hint. ---- admin.py ----- from django.contrib import admin from webpad.models import Layout, Element, LayoutElement, Session, Click, DataGroup, DataElement, ReportTemplate, ReportBlock, Stream, Participant, Observer, Additional from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django import forms class FilteredUserAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user obj.save() def queryset(self, request): qs = super(FilteredUserAdmin, self).queryset(request) return qs.filter(user=request.user) class ElementAdmin(FilteredUserAdmin): fieldsets = [ (None, {'fields': ['name','group','connotation','color','add_to_video']}), ] class AdditionalInline(admin.StackedInline): model = Additional can_delete = False class UserAdmin(UserAdmin): inlines = (AdditionalInline, ) class ParticipantInline(admin.TabularInline): model = Participant extra = 0 class StreamAdmin(FilteredUserAdmin): fieldsets = [ (None, {'fields': ['stream_name','active']}), ] inlines = [ParticipantInline] class LayoutElementInlineForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(LayoutElementInlineForm, self).__init__(*args, **kwargs) self.fields['element'].queryset = Element.objects.filter(user=self.request.user) class LayoutElementInline(admin.StackedInline): model = LayoutElement extra = 0 form = LayoutElementInlineForm def queryset(self, request): self.form.request = request class LayoutAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(LayoutAdminForm, self).__init__(*args, … -
Use PyCharm create a website project, but do not find the db.sqlite3 file
I use PyCharm create a website project, but do not find the db.sqlite3 file. The database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
Django : Signals with a extend User model
I am in Django 1.11 and my question is quite simple : I read these posts : Extending the User model with custom fields in Django https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html and I am not sure a StudentCollaborator user will be created/updated when a user exists (there is already users in the database so I cannot simply redo stuff ). My current code looks like this : # Create your models here. class StudentCollaborator(models.Model): # https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model user = models.OneToOneField(User, on_delete=models.CASCADE) """" code postal : pour l'instant que integer""" code_postal = models.IntegerField(null=True, blank=False) """" flag pour dire si l'user a activé le système pour lui """ collaborative_tool = models.BooleanField(default=False) """ Les settings par défaut pour ce user """ settings = models.ForeignKey(CollaborativeSettings) def change_settings(self, new_settings): self.settings = new_settings self.save() """ https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html#onetoone """ """ Signaux: faire en sorte qu'un objet StudentCollaborator existe si on a un modele """ @receiver(post_save, sender=User) def create_student_collaborator_profile(sender, instance, created, **kwargs): if created: """ On crée effectivement notre profile """ StudentCollaborator.objects.create( user=instance, collaborative_tool=False, settings=CollaborativeSettings.objects.create() # Initialisé avec les settings par défaut ) Can you help me ? Thanks -
settings. DATABASES is improperly configured. Please supply the NAME value
by django /// made cookiecutter python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_co mmand_line utility.execute() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\core\management\commands\makemigrations.py", line 109, in handle loader.check_consistent_history(connection) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\migrations\loader.py", line 276, in check_consistent_hi story applied = recorder.applied_migrations() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\migrations\recorder.py", line 65, in applied_migrations self.ensure_schema() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\migrations\recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 231, in cursor cursor = self.make_debug_cursor(self._cursor()) File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 204, in _cursor self.ensure_connection() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 199, in ensure_connection self.connect() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\base\base.py", line 170, in connect conn_params = self.get_connection_params() File "C:\Users\Taein\.virtualenvs\Taein-VUbYBZJz\lib\site-packages\django\db\backends\postgresql\base.py", line 158, in get_connecti on_params "settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. settings by base.py DATABASES = { 'default': env.db('DATABASE_URL', default='postgres://nomadgram'), } DATABASES['default']['ATOMIC_REQUESTS'] = True I'm not sure why it matters. Please help me. Or will this not happen at all? Am I just too confused/tired at this point? enter image description here <- my database in pgadmin -
Django and REST API serializer of various derived classes
I am solving an equivalent problem to the following. I need to serialize django models which have following criteria: Base (abstract) class from django model containing a "type" field where I can store type of goods (i.e. fruit, clothes...) Derived classes for different type of goods (fruit has weight, clothes have color) I would like to serialize (into JSON) the list of any goods for REST API framework. I do not know how to make it the best to use framework capabilities of serialized object validation etc. -
OpenCV video livestream over HTTP
I'm recently started working on image processing using OpenCV library with python wrapper. Now I want to broadcast original frame and processed frame on server. I need help to decide compatible technologies to implement my goal. After several hours of searching I guess to use: NGINX as server engine UWSGI + DJANGO as backend framework HLS as protocol to send video over HTTP Video.js on client side to play live stream Please, can you give me advise or suggest me anything else?