Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create and download CSV from Django Template
I'm fairly new to Django and haven't done much with serving files and have only ever pulled and pushed from forms using Django Templates. My goal is this: Using the information collected in a form from the user, query my DB and create a CSV that will download to the user. Is this possible with a template based page? -
Python Django encode french accented character when saving but Django admin works
I'm working with french content. I have integrated the Django Admin into my project. MySQL is my database... When i add a new Product (Model) from the Admin board the special characters a saved into the database correctly. But when i call the method save() on the model myself the characters are somehow encoded in something like this \xe90 I'm using Beautifulsoup to crawl contents on the web.... -
Extending User Model Django
I am trying to associate every user with a user profile that has info such as bio, location and birthday. I want those fields to be filled out the same time as the actual User model registration. models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class RegistrationForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User #model User comes with username, email, first name, last name , pass1 and pass2 fields fields = ( 'username', 'email', 'first_name', 'last_name', 'password1', 'password2' ) def save(self, commit = True): user = super(RegistrationForm, self).save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] #note password is saved automatically in User models original save() # function, everything else needs to be done manually as done above if commit: user.save() return user class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('location','bio') … -
How is the Bitnami djangostack created and is it a virtualenv?
I have used the Bitnami Djangostack before but I am not sure if this creates some type of virtualenv or what is the underlying mechanism on how it works or how it is put together. -
Sourcing/Activating Python VirtualEnv in a Bash Script
I am trying to write a simple script that will help me activate (source) the virtualenv and set some environment variables at the same time. Below is the current version that does not yet have any environment variables. #!/bin/bash if [ -z "$BASH_VERSION" ] then exec bash "$0" "$@" fi # Your script here script_dir=`dirname $0` cd $script_dir /bin/bash -c ". ./django-env/bin/activate; exec /bin/bash -i" The trouble with this script is two-fold. When I run it - seemingly successfully as it changes the command line prefix to (django-env) - it is missing the My-Computer-Name: in front of it. Obviously, it is an indication of something as I typically have (django-env) My-Computer-Name: as the prefix. It does not activate the virtualenv properly. Namely, when I check which python, I am notified that the virtualenv Python is used. On the other hand, when I check for which pip or which python3, the global system's Python is used. What can I do to fix these things and have the environment be activated? -
TypeError when saving a Django model that contains an ImageField
I have a basic model for which I've added an ImageField. class Category(models.Model): name = models.CharField(max_length=200, unique=True) slug = models.SlugField(blank=True, editable=False) image = models.ImageField(upload_to='images', blank=True) def __str__(self): """ Field to show in the related models admin site. """ return self.name class Meta: # order of drop-down list items ordering = ('name',) # plural form in admin view verbose_name_plural = 'categories' def save(self, *args, **kwargs): """ Save slug when saving model. Slug saved only if not existant, to avoid duplicity of urls. """ if not self.id: # new object to create self.slug = slugify(self.name)[:50] super().save(*args, **kwargs) When I try to create/update an item from the admin section by setting an image in the ImageField, I get the following error (this error doesn't appear when the ImageField isn't set): Internal Server Error: /admin/quotes/category/8/change/ Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/usr/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.6/site-packages/django/contrib/admin/options.py", line 544, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/utils/decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/lib/python3.6/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/lib/python3.6/site-packages/django/contrib/admin/sites.py", line … -
Django form not displaying name and email fields
I am trying to learn how to use the User class and have made a form, but cant get it to display the email, first_name and last_name fields, I have the following code: forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(required = True) class Meta: model = User fields = ( 'username', 'email', 'first_name' 'password1', 'password2' ) def save(self, commit = True): user super(UserCreationForm, self).save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm def index(request): return HttpResponse('index page') def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('accounts') else: form = UserCreationForm() return render(request, 'accounts/register.html', {'form': form}) # Create your views here. register.html: {% extends 'accounts/base.html' %} {% block head %} <title> Sign Up</title> {% endblock %} {% block body %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} When I go to /accounts/register a form with username, password and password confirmation fields appear and the form works and saves to the database. But where … -
Ubuntu 16.04 Server error about wsgi module in wsgi.py
I'm gonna set a django app on a ubuntu server in a virtual host I have configured my virtual host so that something comes up! I get 500 internal error because some issues as you see here: mod_wsgi (pid=31972): Target WSGI script '/var/www/mmcba/mmemp/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=31972): Exception occurred processing WSGI script '/var/www/mmcba/mmemp/wsgi.py'. Traceback (most recent call last): File "/var/www/mmcba/mmemp/wsgi.py", line 25, in <module> application = django.core.handlers.wsgi.WSGIHandler() File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/wsgi.py", line 151, in __init__ self.load_middleware() File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/usr/local/lib/python3.5/dist-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/middleware.py", line 4, in <module> from django.contrib.auth.backends import RemoteUserBackend File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/backends.py", line 4, in <module> from django.contrib.auth.models import Permission File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 110, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 247, … -
Assertionerror because of custom user model and django allauth
I am a fresher in django(version - 1.10). I am using allauth app in the frontend for registration. I am getting an error in the frontend while signing up. assert not EmailAddress.objects.filter(user=user).exists() AssertionError https://github.com/pennersr/django-allauth/blob/master/allauth/account/utils.py#L251 models.py looks like this class EmailAddress(models.Model): user = models.OneToOneField(User, unique=True, related_name ='address') email = models.EmailField() verified = models.BooleanField(verbose_name=_('verified'), default=True) primary = models.BooleanField(verbose_name=_('primary'), default=True) class Meta: db_table = 'account_emailaddress' class UserProfile(models.Model, HashedPk): user = models.OneToOneField(User, unique=True, related_name ='profile') job_title = models.CharField(max_length=128, blank=True, null=False, default="") website = models.URLField(max_length=255, blank=True, null=True) organisation = models.CharField(max_length=50, blank=True, null=True, default="") phone_number = PhoneNumberField( blank=True, null=True) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) EmailAddress.objects.create(user=instance, email=instance.email) As far as I can understand that EmailAddress.objects.create a row in emailaddress table with the email,id etc and then allauth tries to create a row with the same email,id. I had to save email in emailaddress table because there is no need to confirm email if the user is added by the admin. Is there any way so that if the user is added by the admin then run the below line else ignore. EmailAddress.objects.create(user=instance, email=instance.email) Also is there any alternative way to create the emailaddress object from admin.py using admin.ModelAdmin. Any help or suggestion … -
Django serialization using natural keys: foreign key to the same model
I have a RelationType model with a foreign key to itself: class TypeManager(models.Manager): def get_by_natural_key(self, slug): return self.get(slug=slug) class RelationType(models.Model): name = models.CharField(_(u"Name"), max_length=100) slug = models.SlugField(_(u"Slug"), max_length=100, unique=True) inverse_relation = models.ForeignKey( 'RelationType', verbose_name=_(u"Inverse relation"), blank=True, null=True) objects = TypeManager() def natural_key(self): return (self.slug, ) Once serialized it produces this kind of JSON: [{ "fields": { "name": "Has got", "inverse_relation": [ "is_in" ], "slug": "has_got" }, "model": "myapp.relationtype" }, { "fields": { "name": "Is in", "inverse_relation": [ "has_got" ], "slug": "is_in" "model": "myapp.relationtype" }] This is logically not loadable by Django: DeserializationError: Problem installing fixture 'myfixture.json': RelationType matching query does not exist. Is there a mean to manage this wisely? -
NOT NULL constraint failed Django CreateView
I would like to accomplish two goals on this project. First, I would like to save the logged-in user as the reviewer. Second, I want to pass the lawyer value from the foreignkey into the review form. (This way, the user can review click on a review link on the lawyer's detail page and review that lawyer and no one else.) I keep getting on the first goal, with this error. error IntegrityError at /lawyers/karlyn-rosemarie-hylton/review/ NOT NULL constraint failed: lawyers_review.reviewer_id Can someone please explain what I am doing wrong and how to fix it? The second goal seems to be very related to the first goal. I am not getting any errors for it. But I want to make sure that I am doing it right. However, I won't be able to tell until I get passed the first error. Any help getting unstuck is much appreciated. models.py from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify from django.contrib.auth.models import User class Lawyer(models.Model): name = models.CharField(max_length=55, default='') picture = models.ImageField(upload_to='media/lawyers/pictures', default='') slug = models.SlugField() def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def save(self, *args, **kwargs): self.slug = (slugify(self.name)) super(Lawyer, self).save(*args, **kwargs) def get_absolute_url(self): return … -
Check if Django url is present or a part of it is present?
The problem is simple. If I want to check if the url like: http://127.0.0.1:8000/discussions is active, I will do, {% url 'discussions:index' as discussions %} <li class="nav-item {% if request.get_full_path == discussions %}active{% endif %}"> <a class="nav-link" href="{% url 'discussions:index' %}">Discussions </a> </li> But I want to make the same nav bar link active for this url too: http://127.0.0.1:8000/discussions/Q15 But I don't have the question id (Q15) in navbar template. How should I compare it so that this becomes for all the urls of type: http://127.0.0.1:8000/discussions/anything/anything2 urls.py app_name = 'discussions' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<question_id>Q[0-9]+)$', views.question, name='question'), url(r'^ask/', views.ask, name='ask'), url(r'^answer/(?P<question_id>Q[0-9]+)$', views.answer, name='answer'), url(r'^delete/(?P<id>[AQ][0-9]+)', views.delete, name='delete'), url(r'^edit/(?P<id>[AQ][0-9]+)', views.edit, name='edit'), url(r'^confirm/(?P<id>[AQ][0-9]+)', views.confirm, name='confirm'), url(r'^vote/', views.vote, name='vote'), } I want it to be true for all of them. -
Django: efficient template/string separation and override
I have a generic Django view that renders a template. The template is in an app which other projects will use. Importing projects will typically subclass the View the app provides. The View has a default template, which does a job with generic wording. 99% of the time, subclassing Views will want to only change the text, so rather than make them duplicate the template for the sake of altering non-markup wording, i'm looking for a way to allow users of the class to replace wording in the template in the most efficient way. Options explored so far: template partials containing only the text which using apps can override (magic, a lot of user work) A template_strings method on the view which provides a dict of strings which end up in the template context which subclasses can override Using (abusing?) the translation system such that the app provides default english translations and using code can provide their own translations instead (not actually worked this one out yet, just an idea) Doing the above template_strings through AppConfig, but this seems ... yucky like it may get very unweildy with a lot of English strings. If doing this I would create a … -
django what variables available in a template .html file?
I'm trying to figure out what objects and variables are available within the template .html file This is in the view file from django.contrib.auth import get_user_model Userx = get_user_model() class ProfileDetailView(DetailView): template_name ='profiles/user.html' def get_object(self): username = self.kwargs.get("username") if username is None: raise Http404 return get_object_or_404(Userx,username__iexact=username, is_active=True) In the user.html file {% block content %} username={{ user.username }} {% endblock content %} my questions 1. why is the name of the object in the user.html file called user? how would one find documentation on the object names and fields of the user object? how would one see all available variables accessible in a particular .html template" Thank you for your help -
How can I display an jupyter notebook on a bootstrap homepage?
Evironment: Python 3.6 Django 1.11 I saved a .ipynb file as .html because I want to implement this html to show it on my homepage (that is not yet online). I use bootstrap 4.0 beta as a style on my homepage. I have a navbar that is inherited into any html file of this project which works perfectly fine. But the html file of the jupyter notebook can only be displayed correctly when I do not inherit the navbar. If I try to inherit, the navbar is not displayed correctly anymore. My plan is to build my own blog where I post either markdown files (when I do not include Python or R code) or jupyter notebook or rmarkdown notebook. Both RMarkdown or Jupyter Notebooks can be converted to html, markdown or also pdf. But having tried the first 2, it does not work. If opened in a browser, they are displayed perfectly as you all know. But of course I want to maintain the navigation that I already implemented. So I hope you can give me a hint how I can do that. I have been busy with this for 3 workdays now (I am still a beginner, especially … -
Django,debug True or False
I try to follow tutorial from Udemy,Learning Django from Scratch.I have come to this point OK,then I change DEBUG in settings file to False.After that at localhost Not Found The requested URL / was not found on this server. Why? -
Django Queryset filtering pk list over Manytomany
I want to take a Queryset of Project.objects.all() and filter all Projects that contain a list of attributes chosen by the user. models.py class Attribute(models.Model): title = models.CharField(max_length=20) class Project(models.Model): title = models.CharField(max_length=30) attributes = models.ManyToManyField(Attribute) ## For the sake of this example, there are two Projects and two Attributes ## Project1 is associated to attr1 and attr2 ## Project2 is associated to attr1 I found this: Django Docs Complex Lookups with Q objects and through other stackoverflow answers got to here: Non-working Code (self.multiselect is a list of pks) query = reduce(operator.and_, (Q(attributes__pk=selection) for selection in self.multiselect)) return queryset.filter(query) However this code provides an empty Queryset. I started doing some testing in the interactive shell to figure out what went wrong. Tests queryset = Project.objects.all() ########## & is not working queryset.filter(Q(attributes__pk=1) & Q(attributes__pk=2)) # [] ########## | has no issues queryset.filter(Q(attributes__pk=1) | Q(attributes__pk=2)) # [<Project: Project1>, <Project: Project2>, <Project: Project1>] ########## & works on Project but not on Attribute queryset.filter(Q(title__contains="Project") & Q(title__contains="1")) # [<Project: Project1>] It seems like & is not working on the ManytoMany relation between Project and Attribute. Is there a reason for this, is there a simple fix to the code that will make it work … -
How to use django template tags in jinja
Help, please. I have Django project with jinja2 templates. Need to implement Twitter style pagination. I use library - Django EL(Endless) Pagination. How i can use this templatetags in jinja2 template? {% load el_pagination_tags %} {% paginate entry_list %} {% for entry in entry_list %} {# your code to show the entry #} {% endfor %} {% show_more %} Or perhaps there is an easier way to implement this?? Thanks. -
django - SplitDateTimeWidget return validation error
I want to split date and time in modelForm by this code: class registerMeeting(forms.ModelForm): class Meta: model = Meeting fields = '__all__' widgets = { 'start_date': forms.SplitDateTimeWidget(), 'end_date': forms.SplitDateTimeWidget() } in template date and time rednder splited but when i try to POST an entry return me this error: start_date Enter a valid date/time end_date Enter a valid date/time views.py def register_meeting(request, year, month, day): if request.method == 'POST': form = registerMeeting(request.POST) if form.is_valid(): form.save() return HttpResponse("add") else: form = registerMeeting( initial = { 'end_date': dt.datetime(int(year), int(month), int(day)), 'start_date': dt.datetime(int(year), int(month), int(day)) } ) return render(request, 'meeting_room_reservation/registerMetting.html', {'form':form, 'meetings':meetings} ) -
How can I order query results by which field matched in Django
I've created a search field that will search posts for a term in the title or description, and returns a list of all posts that match. def search(request): term = request.GET.get('q') posts = models.Post.objects.filter( Q(title__icontains=term) | Q(description__icontains=term) ) return render(request, 'posts/post_list.html', {'posts': posts}) This works, but I'd like to order the results so that posts with titles that contain the search term show up first, followed by those where titles do not contain the search term but the description does. I tried creating two queries and unioning them like so: good_matches = models.Post.objects.filter( Q(title__icontains=term)) just_ok_matches = models.Post.objects.filter( ~Q(title__icontains=term) & Q(description__icontains=term) ) posts = good_matches | just_ok_matches But the order seems to be unchanged from the first example. This SO answer seems to cover how to do this with raw SQL, by creating a scoring system. Perhaps there's a way to implement this with Django's ORM? -
No password set. django save user without form
Sorry for my english. Now i learning django rest, and i not clearly understand how save user. For example: i want you send json to server and server save new user {"username": "bob", "password":"123321"} in views i writed method for save user @csrf_exempt def request_user(request): if request.method == "POST": try: data = JSONParser().parse(request) except: return JsonResponse({'message' : 'incorect json format'}, safe=False) serializer = ProfileSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) my serializers class ProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') but in admin i see: No password set.. Why my user save without password? -
How do I rename a model with Django?
Let's say I have this model: class Foo(models.Model): name = models.CharField(max_length=255) I want to rename it to Bar. Any other model from my code doesn't reference this model. What steps should I take? And how do I deal with The following content types are stale prompt? -
QuerySet.union() django 1.11.4
Django 1.11 introduced cool feature to combine querysets. You can make something like: combined_qs = qs1.union(qs2, qs3) And voila! combined_qs has all querysets together keeping their order (btw, am I right here?). I need this, as qs1 should be the first, qs2 the second and so on. But the challenging part is those querysets can't be ordered by any field. As I get it, it happens due MySql ignores any ORDER BY statements in UNION, and it can be done only via subquery. And I don't get it how it can be done via Django ORM without too much raw SQL magic. Any ideas on how those querysets can be unioned with respect to their order_by() statements? -
Django Meta unique_together with related model ManyToOne?
How do you include in Django's meta unique_together a field from a related model where that field is a foreignkey? And can that field from the related model be part of a primary key? Here is the code, class A(models.Model): field1 = models.CharField() class Meta: unique_together = ('field1') # can I add field2 here class B(models.Model): field2 = models.ForeignKey('B') -
TypeError: 'Notification' object is not iterable
i am new to django. i am stuck with an error "object is not iterable". plz help me out.. //view.py class NotificationList(APIView): def get(self,request,user_id,format=None): noti = Notification.objects.filter(user_id=user_id) val=[] for n in noti: serializer = GetNotificationSerializer(n,many=True) in_id = serializer.data.get('interest_id') // this statement makes error //serializer.py class GetNotificationSerializer(serializers.Serializer): interest_id = serializers.PrimaryKeyRelatedField(queryset=Interest.objects.all()) user_id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) article_id = serializers.PrimaryKeyRelatedField(queryset=Article.objects.all()) status = serializers.IntegerField(required = True) //model.py class Notification(models.Model): interest_id = models.ForeignKey(Interest, on_delete=models.CASCADE) user_id = models.ForeignKey(User, on_delete=models.CASCADE) article_id = models.ForeignKey(Article, on_delete=models.CASCADE) status = models.IntegerField()