Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT NULL constraint failed: music_song.album_id
I am using django 1.11.6 and python 3.6.2 I'm new to django and there is no one to help me where i live so you guys are all my hope in my django application in the add song section i faced an error error message = IntegrityError at /music/album/5/AddSong/ NOT NULL constraint failed: music_song.album_id here is my views file: from django.views import generic from django.views.generic import View from .forms import UserForm from django.views.generic.edit import CreateView,UpdateView,DeleteView from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from .models import Album, Song from django.core.urlresolvers import reverse_lazy class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' context_object_name = 'album' class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class SongCreate(CreateView): model = Song fields = ['song_title', 'file_type'] class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' #display a blank form def get(self,request): form = self.form_class(None) return render(request,self.template_name, {"form": form}) #procces form data def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() … -
Log out every logged in user in django
I have one situation in which if admin performs any particular action I need to log user out. I know one that is remove authentication token from the database. is there any other way to do it? thank you in advance. -
Django - Enter a list of values - ManytoManyField
I made the supplier field a select dropdown box since I want it to behave that way but it produces an error: Enter a list of values my model class Product(models.Model): name = models.Charfield(max_length=250) supplier = models.ManytoManyField(Supplier) my form: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'supplier'] widgets = { 'supplier': forms.Select() } def clean_supplier(self): return [self.cleaned_data['supplier']]] It displays the error: Enter a list of values -
Django : Retrieve objects from relation
I am new in Django (1.11 used) and I read this (https://docs.djangoproject.com/fr/1.11/topics/db/models/) but I didn't find a clear answer for my question : How to retrieve the objets With an example , Suppose I have the following models : class StudentCollaborator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) code_postal = models.IntegerField() collaborative_tool = models.BooleanField(default=False) def get_skills(self): return SkillHistory.objects.filter(student=self.user, value="acquired").values_list('skill') The skill history : class SkillHistory(models.Model): """ The reason why a Skill is acquired or not, or not yet, when and by who/how """ skill = models.ForeignKey(Skill) """The Skill to validate""" student = models.ForeignKey('users.Student') """The Student concerned by this Skill""" datetime = models.DateTimeField(auto_now_add=True) """The date the Skill status was created""" value = models.CharField(max_length=255, choices=( ('unknown', 'Inconnu'), ('acquired', 'Acquise'), ('not acquired', 'None Acquise'), )) """The Skill status : unknown, acquired or not acquired""" content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() reason_object = GenericForeignKey('content_type', 'object_id') reason = models.CharField(max_length=255) """Why the Skill is validated or not""" by_who = models.ForeignKey(User) class Meta: ordering = ['datetime'] and finally the skill class : class Skill(models.Model): """[FR] Compétence A Skill can be evaluated through questions answered by a student. Thus, when evaluated, a Skill can be acquired by a student, or not. """ code = models.CharField(max_length=20, unique=True, db_index=True) """The Skill reference code""" … -
django 'str' object has no attribute '_meta'
Sorry for my english. I have some data form enother server, but i need output this data like json. if i print response it contains in console { 'responseStatus': { 'status': [], }, 'modelYear': [ 1981, 1982 ] } but, if i return this response like HttpResponse i have error AttributeError: 'str' object has no attribute '_meta' this my code: data = serializers.serialize('json', response, ensure_ascii=False) return HttpResponse(data, content_type="application/json") -
How to modify slice of queryset persistently without save
I'm transforming (highlighting query matches) of a content attribute for objects in a search result queryset. When transforming the attribute during enumeration over every object in the queryset the transformation persists, at least for the life of the queryset. For obvious reasons I'm not applying a save, because I only want the transformation to persist for the life of the queryset during the request. The problem arises when I try to optimize the enumeration to a slice of the queryset, then the transformation no longer (temporarily) persists. Is there way to have transformations persist for a slice too? Why are my transformations treated differently for a slice than the full queryset? A slice of a queryset is still a queryset, although it does not have equivalence to the original queryset, even if its a slice of the entire queryset. Using Django 1.11.4 and Python 3.6.3 -
in django ,define MiddlewareMixin class .super(MiddlewareMixin, self).__init__() ?
i see the django source code.but i can't understand the following code class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response in detail,i don't understand super(MiddlewareMixin, self).__init__() what is the effect of this code? who can explain for me? thakns very much! -
django model forms fields template dry
We have a django application with tons of forms with generic template for rendering all form fields. Here is an example of one such form template. {% for field in form %} {% include "templates/_pratial/_field.html %} {% endfor %} _field.html <div class="form-group"> {{ field }} </div> forms.py class MyForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['myfield'].widget.attrs.update({'class' : 'form-control'}) Now we are updating our layout with new html , our form now should look like this <div class="form-group "> <label class="control-label" for="email"> {{ field.label }} </label> <div class="input-group"> <div class="input-group-addon"> <i class="{{ field.?? }}"></i> //fa fa-envelope-o </div> {{ field }} </div> </div> How can i dynamically insert fa fa-envelope-o, without breaking dry Some thing like self.fields['myfield'].icon = "fa fa-envelope-o" in form init and can be easily used in template like {{ field.icon }} -
Django multiple dynamic databases after server startup
I'm new to django and try to figure out what would be the best solution for me to use dynamically multiple databases in django. I know django is able to work with multiple databases registered in the settings.py file but In my case I have one main database (sqlite) which acts as my repository, I created all the models, the rest api viewsets for this one. The user can choose to connect to a database by entering the connection information and then I will need to gather data from this database and insert it to my repository. The user can register multiple databases through the app. How can django work with those dynamic databases? Should I register them in the settings.py? Each view in the frontend maps to a specific database and I will need to switch context between them. Any help or insight would be appreciated, I didn't find anything matching my use case on the internet. -
plain text code parameters VS environment variables for web applications?
When we define settings for web applications, we face the choice to use plain text information on code or to request environment variable. Examples : (Stripe_KEY, Database name, Database password, ALLOWED_HOSTS for CORS, etc.) Concrete example on django : ALLOWED_HOSTS = [os.getenv('ALLOWED_HOSTS', '*')] VS ALLOWED_HOSTS = ['localhost:8000'] -
Django pass variable to URL tag
I am using Django 1.11. I am trying to add a link to a DeleteView template from the UpdateView. There is probably a better way to acheive this than the way I am attempting but I am new to Django and so the way i'm trying is to use a URL to direct to myapp/<pk>/delete/ In my template I have {% url 'calendar_delete' pk=event_id %} In my model I have class Event(models.Model): event_id = models.AutoField(primary_key=True) In my URLs I have url(r'^calendar/(?P<pk>\d+)/delete/$',views.CalendarDelete.as_view(),name='calendar_delete'), With the code as above the template doesnt render due to NoReverseMatch exception. '{'pk': ''}' not found, so its obviously not picking up the event_id from the model. When I hardcode a number in there it will render and the URL will direct me to the DeleteView template. Can anyone advise how I can get the <pk>/event_id into the URL tag? The <pk> exists in the URL of the UpdateView template and I have also tried to extract it from the URL as a variable and pass to the URL tag. I can extract ok but not pass in the variable. Any help on this would be much appreciated, including advice on better methods to use for the desired … -
Elastic search TransportError(400, 'search_phase_execution_exception', 'No mapping found
I am working with elasticsearch-dsl-py and django, and trying to implement the sorting mechanism in Text() field. The query for elastic search is s = Search(using=client, index="pustakalaya", doc_type=DocumentDoc).query("match_all").sort( 'title.keyword', ) # This is throwing error. as shown below. response = s.execute() Even though there is a title field which is a Text() type. I don't know why this is throwing error. If I remove keyword from title.keyword the error will be. TransportError(400, 'search_phase_execution_exception', 'Fielddata is disabled on text fields by default. Set fielddata=true on [title] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead.') My mapping in elastic search is { "_index" : "index", "_type" : "document", "_id" : "b7f029bf-196c-4819-a17f-c2bd424710d8", "_score" : 1.0, "_source" : { "keywords" : [ "science fiction" ], "communities" : [ "literatures and arts" ], "author_list" : [ null ], "publication_year" : "2017-10-30", "year_of_available" : "2017-10-30", "collections" : [ "English Literature" ], "thumbnail" : "uploads/thumbnails/document/2017/10/30/thumb.png", "license_type" : "copyright retained", "created_date" : "2017-10-30T04:56:09.122064+00:00", "abstract" : "as k", "type" : "document", "publisher" : "Shree ram publication", "document_type" : "book", "updated_date" : "2017-10-30T05:02:09.720040+00:00", "document_interactivity" : "yes", "title" : "Mero kabita", "document_total_page" : … -
how to set Session time out in django 1.11
I am trying to set session time_out for admin in my django==1.11 . but it did not work with any of the following i tried please help me for better solution thanks in advanced other then this option if any solution is welcome. SESSION_EXPIRE_AT_BROWSER_CLOSE= True SESSION_COOKIE_AGE = 10 SESSION_IDLE_TIMEOUT = 10 SESSION_SAVE_EVERY_REQUEST = True SESSION_INACTIVITY_TIMEOUT_IN_SECONDS = 10 AUTO_LOGOUT_DELAY = 10 -
Virtual Environment installation Error
When I try to install a virtual environment in my local system. I'm getting this error.Could you please help me out to fix this issue $ pip -V pip 9.0.1 from /home/sysadmin/.local/lib/python2.7/site-packages (python 2.7) $ sudo pip install virutalenv sudo: unable to resolve host sysadmin-Veriton-M200-H61 The directory '/home/sysadmin/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/sysadmin/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting virutalenv Could not find a version that satisfies the requirement virutalenv (from versions: ) No matching distribution found for virutalenv -
DRF - Set max and min value of a Serializer field
I've a serializer where I need to set the min and max value. Currently, this is how I do. class ProductSerializer(serializers.ModelSerializer): class Meta: model = Products extra_kwargs = { 'amount': {'min_value': 10000, 'max_value': 60000}, } This works fine, but I don't want to hardcode it, ie I want to fetch it from the DB, just in case the value changes. I've 2 models. 1) Category which has min & max value in it. 2) Products which has amount and category as a FK. The amount entered should be within the range of min-max. How can this be achieved? For eg:- Anything of this sort. extra_kwargs = { 'amount': {'min_value': Category.min, 'max_value': Category.max}, } -
Django compare queryset from different databases
I need to compare 2 querysets from the same model from 2 different databases. I switched db's on the fly, make 2 querysets and try to compare them (filter, or exclude) # copy connections connections.databases['tmp1'] = connections.databases['ukm'] connections.databases['tmp2'] = connections.databases['ukm'] # get dbs from form db1 = DB.objects.get(pk=form.cleaned_data['db1'].id) db2 = DB.objects.get(pk=form.cleaned_data['db2'].id) # left connection connections.databases['tmp1']['HOST'] = db1.host connections.databases['tmp1']['NAME'] = db1.name articles1 = list(Smdocuments.objects.using('tmp1').only('id').filter(doctype__exact='CQ')) # right connection connections.databases['tmp2']['HOST'] = db2.host connections.databases['tmp2']['NAME'] = db2.name articles2 = list(Smdocuments.objects.using('tmp2').only('id').filter(doctype__exact='CQ')) # okay to chain Smdocuments objects all = list(chain(articles1, articles2)) # not okay to diff sets of objects diff_set = set(articles1) - set(articles2) # not okay to exclude sets from different db articles_exclude = Smdocuments.objects.using('tmp1').only('id').filter(doctype__exact='CQ') len(articles1) diff_ex = Smdocuments.objects.using('tmp2').only('id').filter(doctype__exact='CQ').exclude(id__in=articles_exclude) len(diff4) So, "Model objects" not so easy to manipulate, and querysets between difference databases as well. I see, thats not a good db scheme, but it's another application with distributed db, and I need to compare them. It's would be enough to compare by one column, but probably compare full queryset will work for future. Or, should I convert queryset to list and compare raw data? -
what are sockets - uwsgi / nginx - django
I am going through this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html but i don't know what is the socket file, mysite.sock in this case. Could you tell me what is this file and what should be inside ? thanks -
Django migrate command fails with change in foreign key related name
I have a model with a foreign key field. I want to give the foreign key a related name. However, migration fails because of the following error: IndexError: list index out of range I'm using Django==1.10.5 Database backend is PostgreSQL models.py Before/After migrations Before: class Contest_participants(models.Model): contest = models.ForeignKey(Contest) After: class Contest_participants(models.Model): contest = models.ForeignKey(Contest, related_name='contests') The makemigrations command works fine, but the migrate command fails with the above noted error. Complete Traceback Error: Running migrations: Applying teams.0013_auto_20171031_1225...Traceback (most recent call last): File "manage.py", line 19, in <module> execute_from_command_line(sys.argv) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 204, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 495, in alter_field old_db_params, new_db_params, strict) File "/home/aps/Documents/neuron/venv/lib/python3.5/site-packages/django/db/backends/postgresql/schema.py", line 117, in _alter_field new_db_params, strict, File … -
FB.ui with method 'send' do not take the website image while opening a send box
I am trying to invite the friends using Facebook FB.UI. I have successfully added the link of the website. but I could see the application image on the invite box. I have tried something like this: document.getElementById('invite').onclick = function() { FB.ui({ method: 'send', link: 'http://WebsiteURL:PORT', picture: '{{picture.url}}', }); } I get the following output on the windows with no image: Do let me know what to improve. -
Passing user instance from one view to another in django
I am new to django and i am trying to pass user instance from one view to another and then save data in model Category but i get this error: ValueError at /bookmark/category/ Cannot assign "45": "Category.user" must be a "User" instance. bookmark is the name of my application. After registering a new user, he is redirected to another page where he selects category from a dropdown list. I wish to add this selected category in Category model with the same userid. This is my views.py code: def register(request): if request.method == 'POST': form = signUpForm(request.POST) if form.is_valid(): user = form.save() request.session['user'] = user.pk return render(request,'category.html') def get_category(request): cname = request.POST.get("dropdown1") user = request.session.get('user') obj=Category(user=user,category=cname) obj.save() This is models.py file from future import unicode_literals from django.db import models from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User) category= models.CharField(max_length=100) Can someone please guide if this is the right approach or something else is to be done?Thanks! -
Display images in matrix format in Django
I am trying to display the friend's image from Facebook in a matrix format but getting failed to do so as there are number of responsiveness issues. What I have tried is something like this: <div> {% for friend in fb_friends %} <figure> <img src="{{friend.pic}}" height="auto" style="max-height: 50px" width="30%" > </figure> {% endfor %} <!-- other anchors here ... --> </div> This results in the following: The images are hidden by the black color to avoid identity revealing. The output what I am expecting to achieve is the following image: Kindly suggest me what I need to improve. -
Django Error when creating model entries with Django shell
My model looks like this. class Test(models.Model): eval_id = models.ForeignKey(Evaluation, on_delete=models.CASCADE) teacher_id = models.ForeignKey(Teacher, on_delete=models.CASCADE) class_id = models.ForeignKey(Class, on_delete=models.CASCADE) score1 = models.IntegerField() score2 = models.IntegerField() class Meta: unique_together = ('eval_id','teacher_id','class_id') Here eval_id,teacher_id and class_id are defined accordingly in their respective models eval_id = models.IntegerField(primary_key=True) teacher_id = models.CharField(max_length=10, primary_key=True) co_id = models.CharField(primary_key = True, max_length=5) I get the below error when I try to create an entry for the model via the shell from trial.models import Test >>> t1 = Test('1','AC23002','C001','48','50') I get the below error Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 904, in _save_table forced_update) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/base.py", line 954, in _do_update return filtered._update(values) > 0 File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/query.py", line 664, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 1199, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 871, in execute_sql sql, params = self.as_sql() File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/sql/compiler.py", line 1165, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/related.py", line 963, in get_db_prep_save return self.target_field.get_db_prep_save(value, connection=connection) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", line 762, in get_db_prep_value value = self.get_prep_value(value) File "/usr/local/lib/python2.7/dist-packages/Django-1.11.5-py2.7.egg/django/db/models/fields/__init__.py", … -
Django URL Regex Exact Match Only (Basic Regex)
I am new to django and trying to build my first API. The url structure is as follows but the problem is: when the first part of the URL matches, it calls that one. Ex. If I call 'welcome/example' it matches with welcome and doesn't make it to the actual welcome/example... from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^login/', include('shopify_app.urls')), url(r'^', include('home.urls'), name='root_path'), url(r'^admin/', admin.site.urls), url(r'^welcome/', views.welcome), url(r'^welcome/example', views.create_example), #regex not working ] -
can we edit snippet plugin in django cms ? if yes then how?
I am adding HTML in my page using djangocms_snippet I want snippets that I have created for first page should not be shown in another page while adding snippet there. Is there another plugin present through which I can achieve these or there is any way by which I can edit djangocms_snippet plugin. -
How to display a MySQL blob image in html in django?
I have a mysql blob image in my database and I want to show it in html. I retrieved the blob in my views.py using raw SQL query and passed it to my my html page as a dictionary object.I have not used models so please refrain from giving an answer using models.