Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing website background for bootstrap template
I'm doing some tutorials on web development with Django (I'm a complete beginner). I have downloaded this bootstrap theme and succesfully implemented it for my future website. What I would like now is to personalise this bootstrap theme by changing the default background. The "grayscale" theme css is referred to like this: <!-- Theme CSS --> {% load staticfiles %} <link href="{% static 'aboutme/css/grayscale.min.css' %}" rel="stylesheet"> (I'm sure that this is what gives my webpage the grayscale theme, since when I delete these lines, the grayscale theme on my website is gone.) Looking in the "grayscale.min.css" file, I find the following line: {display:table;height:auto;padding:100px 0;text- align:center;color:#fff;background:url(../img/intro-bg.jpg) bottom center no-repeat #000;-webkit-background-size:cover;-moz-background- size:cover;background-size:cover;-o-background-size:cover} I guess this is where the background is set since the intro-bg.jpg in the img map is the grayscale background picture. However, when I try to change the background like: background:url(../img/mybackground.jpg) It doesn't work! The strange thing is that it seems like the site doesn't need the "grayscale.min.css" file at all; when I delete all its content and save it, nothing changes for my site! I don't get this since, like I mentioned earlier, when I delete the line: {% load staticfiles %} <link href="{% static 'aboutme/css/grayscale.min.css' %}" rel="stylesheet"> The … -
How to open a pdf file in binary format
I want to read the metadata of pdf files so i am using pyPdf package but for some files i am facing error (i.e;PdfFileReader stream/file object is not in binary mode,it may not be read correctly) I am a begginer it will be helpful to me,thank you in advance -
Update User table in Django database
I'm trying to update user in Django database. Fetched data is as follows : fetched_data = { 'id': 1, 'first_name': 'John', 'last_name': 'Doe', 'phone': '+32 12', 'mobile_phone': '+32 13', 'email': 'myemail@hotmail.com', 'username': 'myusername' } I get the user with this id as follows : old_user = User.objects.get(pk=fetched_data['id']) If I update the user as follows : old_user.username = fetched_data['username'] old_user.first_name = fetched_data['first_name'] ...... old_user.save() it works fine, but I do not want to do it for every record, thus I tried something like : for fetched_data_key in fetched_data: old_user.fetched_data_key = fetched_data['fetched_data_key'] //old_user[fetched_data_key] = fetched_data['fetched_data_key'] --- I tried this way to old_user.save() But that doesn't work. Any idea how can I update the user without doing it for every record? Thanks in advance. -
django models HTML allows
from django.utils import timezone i have this in models.py class Poll(models.Model): id = models.AutoField(primary_key=True) id_curse=models.IntegerField() enum=models.CharField(max_length=1000) feedback=models.TextField() expiration_date=models.DateTimeField(default=timezone.now) my question is: How do I make the enum field accept characters (+255) and allow me HTML content -
How to save both JSON and file to the model with Django
I have a working code that saving JSON to my model I'm making multipart uplost from iOS where append two body parts: the first part is "image/jpg" and the second one is utf-8 encoded JSON "Content-Type": "multipart/form-data" So from iOS part everything is OK, and I've got success with decoding json and saving it to the model, but I have problem with the image saving In fact I have request.POST['file'] - this is the file, and I think that it should be saved somewhere inside WriteIssueSerializer but I don't know the way how to do it, becouse WriteIssueSerializer's argument is a dictionary only... Here is my python code : Model: class Issue(TimeStampedModel): title = models.CharField(max_length=255, null=False) description = models.TextField(null=True) reported_by = models.ForeignKey(OfficeUser, on_delete=models.PROTECT, related_name='reported_issues') assigned_to = models.ForeignKey(OfficeUser, on_delete=models.PROTECT, related_name='assigned_issues') SEVERITY = Choices( (0, 'Cosmetic', _('Cosmetic')), (1, 'Low', _('Low')), (2, 'Normal', _('Normal')), (3, 'Major', _('Major')), (4, 'Critical', _('Critical')) ) severity = models.IntegerField(choices=SEVERITY, null=False, default=SEVERITY.Normal, db_index=True) PRIORITY = Choices( (0, 'Idle', _('Idle')), (1, 'Low', _('Low')), (2, 'Normal', _('Normal')), (3, 'High', _('High')), (4, 'ASAP', _('ASAP')) ) priority = models.IntegerField(choices=PRIORITY, null=False, default=PRIORITY.Normal, db_index=True) attachment = models.FileField(upload_to='uploads/', blank=True) STATUS = Choices( (0, 'New', _('New')), (1, 'Assigned', _('Assigned')), (2, 'InProgress', _('In Progress')), (3, 'Completed', _('Completed')), (4, … -
Django template- commented script is displayed on page- why?
I have a Django template, on which I am displaying some 'PDF' reports in a 'tabbed' display section (a separate/ different tab for each report). Although the content that I want displayed on the each of the reports is currently displayed, for some reason, there is some commented Django template code also displayed on the reports: I have searched through my project, and found that the script that's being displayed in the 'PDF' (report) part of the page (i.e. the {#% block content_ccis_pre_deposit %} that you can see in the screenshot) is coming from the template for that page. But it seems that the script that's being displayed is actually script that I have commented in my template file... The structure of the template file, and location of the commented script is: <!DOCTYPE html> <html id="pdf"> <head> ... </head> <body> ... <pdf:nextpage /> {#Add a block for content_ccis_pre_deposit #} {#% block content_ccis_pre_deposit %} {% if not webview %} <table> <tr> <td> <a class="plain-link" href="{% url 'costing:home' project.id %}">Client Choice Items - please refer to 'Budget Explained' </a> </td> <td rowspan="2" style="text-align: right;"> </td> </tr> <tr> <td> <span class="project-name">{{project.project_name|upper}}</span> </td> </tr> </table> {% endif %} <table class="pdf-report left"> <thead> <tr> <th … -
django - authenticate users using django.test.Client
In my tests, I am trying to create and authenticate a User but when I hit my views, it still returns 302 def test_Home(self): self.client = Client() self.user = User.objects.create_user("xoxo", password="bar", is_staff=True) self.logged_in = self.client.login( username="xoxo", password="bar") r = self.client.get('/hudson/') self.assertEqual(r.status_code, HTTP_200_OK) My /hudson/ view is simply: class HomeView(PermissionRequiredMixin, generic.TemplateView): template_name = 'foo/base.html' permission_required = ('user.is_staff', ) login_url = reverse_lazy('admin:login') I am getting 302 to my admin/login as define in the view. -
How to combine two filters in Django REST Framework
I'm trying to combine two filters which referred to a FK in an object but I'm getting wrong and redundant data. Below presented the filters: class RecordFilter(df.FilterSet): user = df.CharFilter(name='active_states__user', method='filter_user') activestate = df.BooleanFilter(name='active_states__is_active', method='filter_is_active') class Meta: model = Record fields = ['type', 'group', 'user', 'activestate'] def filter_user(self, queryset, _, value): return queryset.filter(active_states__user_id=value) def filter_is_active(self, queryset, _, value): return queryset.filter(active_states__is_active=value) For example I tried to test these filters for user=user2 and activestate=True using the following data: record1.set_active_states_for_users([user1.uuid], True) record2.set_active_states_for_users([user1.uuid], False) record2.set_active_states_for_users([user2.uuid], True) record3.set_active_states_for_users([user2.uuid], False) And I'm getting Two times the record2 because of activestate=True and user=user2 One time the record3 because of user=user2 The correct result should be only one time the record2. -
django - use method on every object in queryset like filter '__in' custom manager
Hello I would like to implement method for player to take list of players (query set) and leave clan I'm looking for something like: Player.leave_clan([1,2,3]) Player.leave_clan([p1,p2,p3]) What I have tried is the method which takes list of account_ids [1,2,3] and then I use updated method on query, but here I have to pass only account IDs def remove_leavers(self, leavers, clan): players = Player.objects.filter(account_id__in=leavers) players.update(clan=None, previous_clan=clan) and with my current models I could call something like: leavers = Player.objects.filter(account_id__in=[1,2,3] for player in leavers: player.leave_clan() But I do not think it's right way to do. I use following models down bellow, thank you for all suggestion and recommendations. I think I need custom manager but I did not know how to write it even after reading the documentation. from django.db import models class Clan(models.Model): clan_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) tag = models.CharField(max_length=5) def __str__(self): return "{tag}".format(tag=self.tag) @property def members(self): return Player.objects.filter(clan=self) def kick_player(self, player): player.leave_clan() class Player(models.Model): account_id = models.IntegerField(primary_key=True) account_name = models.CharField(max_length=250) clan = models.ForeignKey('Clan', on_delete=models.CASCADE, blank=True, null=True, related_name='current_clan') previous_clan = models.ForeignKey('Clan', on_delete=models.CASCADE, blank=True, null=True, related_name='previous_clan') def __str__(self): return '{0} - {1}'.format(self.account_name, self.account_id) def leave_clan(self): self.previous_clan = self.clan self.clan = None self.save() -
i want to get username and email from user not social when user signup by social login (django_allauth)
I want to get username and email from user not social(kaka). because the social doesn't provide email address and username. so if user logined by social, he's username is like 'user17'. I was googling, I have thought that i can use ACCOUNT_SIGNUP_FORM_Class but it doesn't work could you help me? this is my forms.py from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ # If you don't do this you cannot use Bootstrap CSS class SignupForm(forms.ModelForm): username = forms.CharField(label="Username", max_length=30, widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'username', 'placeholder' : 'Username'}), required=True, help_text=_("Required.")) email = forms.EmailField(label=_("Email address"), widget=forms.EmailInput(attrs={'class':'form-control', 'name': 'email', 'placeholder':'이메일'}), required=True, help_text=_("Required.")) class Meta: model = User fields = ('username', 'email') def signup(self, request, user): user.username = self.cleaned_data['username'] user.email = self.cleaned_data['email'] user.save() -
Django: Access Model fields in template when using form.ModelMultipleChoiceField
It is a follow up to this question and answer. My question now is, when I have a ModelMultipleChoiceField in my form how do I access all of the model fields of a passed queryset in template? Currently my form is: class CarChoicesForm(forms.Form): def __init__(self, *args, **kwargs): cars = kwargs.pop('cars', None) super(CarChoicesForm, self).__init__(*args, **kwargs) self.fields['cars']=forms.ModelMultipleChoiceField(queryset=cars, widget=forms.CheckboxSelectMultiple) Template: <tbody> {% for choice in form.cars %} <tr> <td>{{ choice.choice_label }}</td> <td><span class="checkbox">{{ choice.tag }}</span></td> </tr> {% endfor %} </tbody> It only prints what Car.__str__() provides, but I need other fields to achieve something like this. I tried {{ choice.choice_label.brand }}, etc. with no success. -
Overriding/Adding to Django URLs in settings rather than urls
It seems that the latest Django debug toolbar module has changed to middleware now and requires explicit URL setup to work. With my Django projects I always try to keep settings organised based on environment and not have if settings.DEBUG littered all over the settings files and project. My settings layout is a general: common.py (everything in here) development.py (dev only things here) production.py (prod only things here) Is there a way in Django 1.10 I can add to the URLs in the development.py file so that I can keep away from if settings.DEBUG. Or will we be forced to use this method if wanting to use the new version of the debug toolbar? I just find the below a bit of an anti-pattern if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] -
Django psycopg2.ProgrammingError relation does not exist using custom model Manager
I'm unable make any migrations from scratch with my current codebase. Running ./manage.py makemigrations reports gives the following traceback Traceback (most recent call last): File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "reports_frozenschedule" does not exist LINE 1: ..._file", "reports_frozenschedule"."abandoned" FROM "reports_f... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/management/base.py", line 342, in execute self.check() File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/home/jwe/Documents/piesup2/venv/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen … -
How to return an empty form in ModelFormMixin
DetailStory subclasses DetailView and ModelFormMixin thus presenting the DetailView of a certain story and a form at the end. However, on filling the form and submitting the data, the data is saved in the databases but it is still shown on the form (in addition to the one now displayed on the DetailView). How do I present an empty form after submitting it? (Here is the code sample) class DetailStory(DetailView, ModelFormMixin): model = Story template_name = 'stories/detail_story.html' context_object_name = 'detail' form_class = CommentForm def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) return DetailView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) if self.form.is_valid(): obj = self.form.save(commit=False) obj.user = self.request.user obj.memoir = self.get_object() self.object = obj.save() return self.get(request, *args, **kwargs) def get_object(self): item_id = crypt.decode(self.kwargs['story_id'])[0] obj = get_object_or_404(Story, Q(privacy='public') | Q(user_id=self.request.user.id), pk=item_id) return obj -
manage.py process not picking up updated database
I start a Django manage.py shell session then start another shell session in a new teminal. If I then update a model instance and save to the database in the second session when I then retrieve the model instance in the first session the update is not present. Is there a way to force the first session to get the latest instance of the model? -
User has no user profile:RelatedObjectDoesNotExist
I am trying to create UserProfile modal by extending default django User. Additional value cannot be saved because User has no user profile:RelatedObjectDoesNotExist: user = User.objects.create_user(username=username, password=password) user.save() print(fb_id) user.userprofile.fb_id = fb_id user.userprofile.save() modal : class UserProfile(models.Model): user = models.OneToOneField(User) fb_id = models.BigIntegerField(null=True, blank=True, default=0) follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) Can't understand why it's wrong and how to do in the right way? Django 1.8 -
Django documentation on development server using Sphinx CSS not working
I'm trying to combine Sphinx on my Django development server. I know i could better use apache. But I can't use apache due to the fact that the project will be managed by someone else and the project needs to work as simple as possible. Without too many external libraries etc. So i tried django-docs package and django.static.serve in my url. The HTML pages work, only the look of the pages is just plain html so the CSS isn't included. The documentation on django-docs is really bad and i can't seem to get it to work with the static files Sphinx created. I can't use sphinxdocs as well since it needs haystacks which will add to my external libraries. I added django-docs to my installed apps and added this to my settings. With projectpath being the path to where my conf.py is located. I'm not sure if the location is right though. But the documentation isn't really clear at what i should fill in on the project path part. And i added the urls in my urlspatterns DOCS_ROOT = os.path.join(PROJECT_PATH, '../docs/_build/html') DOCS_ACCESS = 'staff' url(r'^docs/', include('docs.urls')), In sphinx doc the static files are located in the docs/_build/html/_static Thanks in advance … -
Django:cms no reverse match error
Iam getting the error as follows. NoReverseMatch: Reverse for 'pages-details-by-slug' with arguments '()' and keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: [u'zh-cn/(?P[0-9A-Za-z-_.//]+)/$'] i have set the content management system(CMS) slug in the admin page, it started occurring i think after i tried to install haystack on the same server. Any suggestions? I am using Django==1.6.11, django-cms==3.0 -
How to fileupload in Django Rest Framework?
I want to upload file in Django Rest Framework. I apply to all according to django documentation. views.py def put(self, request, student, format=None): file_obj = self.request.FILES['file'] if file_obj is None: return Response(status=400) filename = '{}/{}'.format(MEDIA_ROOT, file_obj) with open(filename, 'wb+') as temp_file: for chunk in file_obj.chunks(): temp_file.write(chunk) return Response(status=204) models.py class DeliveredHomework(TimeStampModel): file = models.FileField( null=True, blank=True, upload_to=_handle_homework_file, ) I arranged MEDIA_ROOT settings. But the response is coming like this: tmp_00z2ap.upload What is the problem? Thank you. -
Having admin inline for model without direct relation or foreign key
So, I have this these model: class Photo(models.Model): source = models.ImageField(upload_to='uploads/gallery/photo') class Item(models.Model): content_type = models.ForeignKey( ContentType, limit_choices_to={'model__in': ['photo', ]}, on_delete=models.CASCADE, ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Album(Media): items = models.ManyToManyField(Item) How can I have an album admin with photo as inline ? When I tried making inline for photo and hook it to album admin, I get error "photo has no foreignkey to album", pretty obvious, from there I think there should be a way to link foreignkey needed by album admin with content object from model item. -
Check if user has one of the listed permissions in Django
I have the following issue. There is a list of permissions (suppose 'a' to 'z'). Each user has a subset of these permissions. Suppose we have another list, perms_list = [a, c, d] I want to check if the user has at least one of the permissions in perms_list. user.has_perms(perms_list) checks if the user has all the permissions, so, I cannot use this. The alternative is to put this in a for loop for p in perms_list: if user.has_perm(p): # do_something Is there a more efficient way of doing this? As an extension to this question, is it possible have a generalised way of doing this? For example, user should have (perm1 and perm2) or perm3 -
Django internationalization doesn't find .djhtml and .djt templates
I'm using i18n on Django to make my website multilingual. I've recently changed my templates' extensions from html to djhtml, so that Emacs will do syntax highlighting, but after this change, python manage.py makemessages doesn't find the djhtml files (or doesn't consider them as templates) and doesn't create the entries on my django.po file for the translations in them. It even comments out translations that I previously had on html files. If I make an exact copy of the djhtml file in the same folder, but with a html extension, then it works normally. The same thing happens with djt as well. How to I configure i18n to consider djhtml and djt files as templates as well? -
Django Apache mod_wsgi co existing with Wordpress cannot establish database connection
I am trying to deploy a Django app on a Centos server that has Apache and Wordpress. The app is working with the django build in development server with no problem but when i try to deploy with mod_wsgi i get an error: Error establishing a database connection.My guess is that it has something to do with the configuration file and it tries to run the app using wordpress and not mod_wsgi that's why i get this wordpress error but i've been trying and searching how to fix this and i've come to no solution. My configuration files are 2 seperate files in conf.d: django.conf: Alias /static/ /root/mass_update/static/ <Directory /root/mass_update/static> Require all granted </Directory> WSGIScriptAlias /mass_update /root/mass_update/dashboard/wsgi.py <Directory /root/mass_update/dashboard> <Files wsgi.py> Require all granted </Directory> #WSGIPythonPath /var/www/mass_update/:/root/.virtualenvs/dashboard/lib/python2.7/site-packages WSGIDaemonProcess mass_update python-path=/root/mass_update:/root/.virtualenvs/dashboard/lib/python2.7/site-packages WSGIProcessGroup mass_update idash.conf(wordpress): <VirtualHost 172.31.128.20:80> # ServerAlias test DocumentRoot /var/www/idash ServerName idash.test.gr <Directory /var/www/idash> AllowOverride All </Directory> </VirtualHost> settings.py: """ Django settings for dashboard project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See … -
Rendering current page to PDF
I have page which displays some kind of statistical. I'm using ChartJS to render graphics. Now I need to provide way to export this graphs as PDF file. And I have no idea now to implement this. -
Manage.py sqlsequencereset returns nothing
I need to reset auto-increment counters in my db. I'm using django(1.8), DRF(3.3.2) and mysql(5.7.16). As said in docs and other questions on stackoverflow, i use sqlsequencereset to generate SQL code for my needs: manage.py sqlsequencereset example_app or manage.py sqlsequencereset example_app > 1.txt But it returns nothing (or empty string, idk). What do I need to do to make it work?