Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to create a group of reusable apps
I have a group of related apps i would like to keep in a common directory/package. As for now everything worked fine, but the problem is when I want to define AUTH_USER_MODEL as it's not working with a string like package.app.model. I've found some solutions like importing the model in __init__.py but those feels somewhat hacky - i don't have much experience with python or django, but it looks like maybe i'm approaching the problem wrong way? What i would like to acheive is to create a reusable group of apps i could easily drop into few of my projects and update from time to time in some sensible way. Of course i could create just one app, but i don't like that idea as there are going to be some different domains (like accounts, cms, e-commerce, etc) which preferably should be in separate apps. Those projects are going to have some other specific, project-related apps also (that's why i would like to group the core, common base in some form of a package if possible). Also, this won't be any publicly distributed thing - just reusable between few specific projects im doing. What i'm searching for is something simple … -
django rest framework same route, different
i'm using django rest framework to build an api, here is my problem url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'), url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'), class ProfileRetrieveView(RetrieveAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer class ProfileUpdateView(UpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = (IsAuthenticated, ) When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins. -
Django - Check Other Objects Prior to Save
I want to override the built-in django .save() method to perform a check against all other objects in the database. For example: class User(models.Model): name = models.CharField(max_length=120) class Admin(models.Model): name = models.CharField(max_length=120) class SecurityGroup(models.Model): name = models.CharField(max_length=120) users = models.ManytoManyField(User) admins = models.ManytoManyField(Admin) def save(self, *args, **kwargs): # check admins don't exist in any other SecurityGroup prior to save super(Person, self).save(*args, **kwargs) # Call the "real" save() method. The documentation example is pretty simple, and doesn't describe this type of pre-save check. Is it possible to achieve this save functionality internal to the SecurityGroup Model, or do I need to create a form and use SecurityGroup.save(commit=False) for this type of pre-save check? Thanks for the help. -
Queryset in Django if empty field returns all elements
I want to do a filter in Django that uses form method. If the user type de var it should query in the dataset that var, if it is left in blank to should bring all the elements. How can I do that? I am new in Django if request.GET.get('Var'): Var = request.GET.get('Var') else: Var = WHAT SHOULD I PUT HERE TO FILTER ALL THE ELEMNTS IN THE CODE BELLOW models.objects.filter(Var=Var) -
Saving data from Backbone to Django with two parameters
I have to save data with two parameters into this Django model class Employee(Base): language = models.ForeignKey(Language, on_delete=models.CASCADE) employee_img = models.ForeignKey(EmployeePicture, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True, verbose_name='Name') position = models.CharField(max_length=100, null=True, blank=True, verbose_name='Position') description = models.TextField(null=True, blank=True, verbose_name='Description') My url is like: http://website.com/control/employee/18/en/, where the number is the id of employee_img and the en is a field in language. I set my Backbone view like this: module.exports = Backbone.View.extend({ el: '.EmployeeForm', template: template, events: { 'blur input': 'updateValue', 'click .Button--add': 'savedata' }, initialize: function() { this.newModel = new EmployeeModel(app.data.employeeDataInWindowObject); }, updateValue: function(event) { console.log('value updated'); var value = $(event.target).val(); this.newModel.set($(event.target).attr('name'), value); }, savedata: function(event) { event.preventDefault(); this.newModel.save(null, { headers: { employee_img_id: app.data.employeeDataInWindowObject.employeeImg, language_id: app.data.employeeDataInWindowObject.language }, success: function() { console.log('Sucess saving data'); } }); } }); As you can see I retrieve data from an object window.app.data.employeeDataInWindowObject where I saved it previously. My backbone model looks like: module.exports = Backbone.Model.extend({ urlRoot: '/control/api/employee/' }); My Django router: url(r'^employee/$', ApiEmployeeView.as_view()), url(r'^employee/(?P<obj_id>\d+)/(?P<lang>\w+)/$', ApiEmployeeView.as_view()) Am I passing parameters correctly? Thanks! -
templatetag not rendering in template/html
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. I have an array defined as the following checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) When I print my array the console displays it correctly: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() # Calls .getlist() on a querydict # Use: querydict | get_list {{ querydict|get_list:"itemToGet" }} @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) @register.filter def get_at_index(list, index): return list[index] Now i'm trying to get my template to display what's in my console but as individual rows/indexes. I'm told get_list will do that for me. I've also tried get_at_index. Using the following template my app prints correctly, just all on one row because it's an array. {% for app in retreivecheckbox %} {{ app }} {% endfor %} When I try several variations of the following my template displays nothing. Why doesn't my get_list break my array into indexed lines? {% load app_filters %} {% for app in retreivecheckbox|get_list:report_id %} … -
make some django/wagtail files private
Is there a way to make some files unaccessible via direct url? For example, an image appears on a page but the image location doesn't work on it's own. -
Django - AttributeError
I created my custom User model. While doing migrations, I get an AtrributeError from django.db import models from time import timezone from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.mail import send_mail from django.utils.http import urlquote from django.utils.translation import ugettext_lazy as _ class CustomUsermanager(BaseUserManager): def _create_user(self, is_anonymous, first_name, last_name, email, username, password, home_address, user_type, image_path): now = timezone.now() if not email: raise ValueError('The gives emial must be set') email = self.normalize_email(email) user = self.model( is_anonymous=is_anonymous, first_name=first_name, last_name=last_name, email=email, username=username, home_address=home_address, user_type=user_type, image_path=image_path, created_time=now, last_login=now ) user.set_password(password) user.save(using=self._db) return user def create_a_admin(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(1, first_name, last_name, email, username, password, home_address, 0, image_path) def create_a_nonanonymous_patient(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(0, first_name, last_name, email, username, 1, password, home_address, 1, image_path) def create_an_anonymous_patient(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(1, first_name, last_name, email, username, 1, password, home_address, 1, image_path) def create_a_nonanonymous_helper(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(0, first_name, last_name, email, username, 2, password, home_address, 2, image_path) def create_an_anonymous_helper(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(1, first_name, last_name, email, username, 2, password, home_address, 2, image_path) def create_a_prof(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(0, first_name, last_name, email, … -
Django Signal Triggered But Not Saving
Exactly like the title says. The post_save receiver is being triggered, and permissions are being changed in these methods, but they remain unchanged on the admin page. Here's the model I'm using, stripped to just the part in question. from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from guardian.shortcuts import assign_perm, remove_perm class Role(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_admin = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_role(sender, instance, created, **kwargs): if created: Role.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_role(sender, instance, **kwargs): if instance.role.is_admin: assign_perm('auth.add_user', instance) else: remove_perm('auth.add_user', instance) instance.role.save() The if..else in the save_user_role method works in the django shell, but not in my signal. I (don't think) I can save instance again, because that'll cause an infinite loop of post saves. Saving to my Role model didn't work, as permissions have to be save to Users and Groups. I'm guessing this is a misunderstanding of how I'm supposed to use signals, or saving models. Why are my permissions not being saved? What can I do in future to avoid this? -
lastActive feature for Django not working
I am trying to implement a lastActive feature but I don't know what values should the null and blank property have for the lastActive field in the User model. With this version of the code, the lastActive fields get a similar time as the created field, but after every login+logout the lastActive field doesn't get updated. Other than that, I am also getting the following error if I try python manage.py migrate, although makemigrations works fine: File "/Library/Python/2.7/site-packages/django/utils/dateparse.py", line 94, in parse_datetime match = datetime_re.match(value) TypeError: expected string or buffer Here's my models.py: class User(models.Model): userID = models.AutoField(primary_key = True) username = models.CharField(max_length = 30, unique = True) first_name = models.CharField(max_length = 30, blank = False) last_name = models.CharField(max_length = 30, blank = False) email = models.EmailField(blank = False, unique = True) password = models.CharField(max_length = 30) class_year = models.IntegerField(validators=[MinValueValidator(4),MaxValueValidator(4),]) created = models.DateTimeField(auto_now = True, editable = False) #this field actually doesn't get updated yet, please debug lastActive = models.DateTimeField(auto_now = True, editable = True) Here's my middleware.py: class LastActiveMiddleware(MiddlewareMixin): def process_response(self, request, response): if request.user.is_authenticated(): User.objects.filter(pk = request.user.pk).update(lastActive=timezone.now()) return response Here's my view.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.signup(form, request) username = form.cleaned_data.get('email') … -
Python Django user model extension
I want to add phone number feild to user model and I would like to verify email and phone when we add user to the list. I would like to know your comments on it. Make a userapi which will integrate with Google or Facebook for authentication this will also verify phone number using third party. Is my approach correct? If you can provide code snippets on model, apiview it will very useful. Thanks Kay -
psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting these errors: psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("data", "project_id", "pro... What should I change in code to resolve this error? Here's the traceback: Traceback (most recent call last): File "/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column "data" of relation "WorldBank_projects" does not exist LINE 1: INSERT INTO "WorldBank_projects" ("data", "project_id", "pro... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 53, in handle project_abstract = data['project_abstract'] File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table … -
TemplateDoesNotExist at /music/album/2/
Index.html code {% extends 'music/base.html' %} {% block body %} My Albums {% if all_albums %} {% for album in all_albums %} {{ album.album_title }} {{ album.artist }} View Details {% csrf_token %} {% cycle '' '' '' '' '' '' %} {% endfor %} {% else %} Add an Album {% endif %} {% endblock %} url.py code from django.conf.urls import url from . import views app_name='music' urlpatterns = [ #/music/ url(r'^$', views.Indexview.as_view(), name='index'), #/music/123/ url(r'^(?P<pk>[0-9]+)/$', views.Detailview.as_view(), name='detail'), url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'), url(r'album/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'), url(r'album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete'), -
Django data handling in custom middleware
In my django webapp, I have to pass user data param(udp) in a request and return the same in response without modifying it in view. Request { "mobile": "111111111", "udp":[ { "key": "keyName", "value":"valueName" }, { "key": "keyName", "value":"valueName" }, ] } Response { "code": "200", "message": "success message", "response": { "data":"user data" "udp":[ { "key": "keyName", "value":"valueName" }, { "key": "keyName", "value":"valueName" } ] } } I thought of acheiving this by writting custom middleware but after accessing request in middleware, View is throwing me error you cannot access body after reading from request's data stream Can anyone suggest how this can be implemented? or What will be best approach of doing this in django -
How do I track user behaviour/Activity on my website?
I'm working on a big Django project think of it like all social networks combined. I wanted to create a recommendation system and I realised I need data. I'm wanna use Cassandra for this task using Django Cassandra engine but I really don't know what should be the structure of the data should it be like and how do I store it. my biggest concerns are How the data should look like (the structure of unstructured data) Eh. user 4679 most used hashtags Users 5753 visits:- User 123's profile 6 times User 986's profile 34 times User likes post User commented on post contains Keywords Etc etc etc How do I store the data -
Django QuerySet not appearing in HTML file for PythonAnywhere Web App
I'm having a bit of trouble with this part of the DjangoGirls tutorial (about templates). Currently, my website is at chocoberrie.pythonanywhere.com. It's supposed to show a few posts inside the QuerySet, but the list is empty, and I don't know why (or how to fix it). 1) The QuerySet isn't loading at all in the HTML file. I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page. 2) I don't know how to edit the database file on PythonAnywhere. This database file is supposed to be separate from the local db.sqlite3 on my computer (since db.sqlite3 is in the .gitignore file, it's not committed). I read about this here. I understand that this is useful to keep production changes from being displayed on the live website, but how I supposed to have this data on the PythonAnywhere side? What file am I supposed to edit on PythonAnywhere? Thanks for the help, I appreciate it! Here are my local files: urls.py from django.conf.urls import … -
Django 1.11.7: How do I call a method from a Class in Views?
In my models.py I have a Class (Paths) with a method, validate_time that uses the two properties of the Paths model (time_start, time_end): class Paths(m.Model): time_start: m.TimeField() time_end: m.TimeField() def validate_time(self): start = self.time_start end = self.time_end #some function that returns True or False How do I call this method of the Paths class in my views.py? This is what I'm trying: from .models import Paths def paths_data(request): valid_times = Paths.validate_timeslot() if valid_times == False: -
Django selectdatewidget how to render manually?
I'm trying to render a selectdatewidget in django out manually so I can customise with bootstrap. However I'm not clear on how I render out the indvidual inputs with the selectdatewidget? class ProfileForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) eighteen_years_from_now = (datetime.datetime.now().year - 18) date_of_birth = FieldBuilder(User, 'date_of_birth', widget=SelectDateWidget( years=range(eighteen_years_from_now, 1919, -1))) template to render an individual field: <div class="form-group"> <label for="{{ field.id_for_label }}" class="sr-only"> {{ field.label }} </label> {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" placeholder=field.label %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> -
ValueError: invalid literal for int() with base 10: ' ' [Django]
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: ValueError: invalid literal for int() with base 10: '' What should I change in code to resolve this error? Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/python/lib/python3.6/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 "/python/lib/python3.6/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 "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards field, File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 415, in add_field definition, params = self.column_sql(model, field, include_default=True) File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 155, in column_sql default_value = self.effective_default(field) File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 229, in effective_default default = field.get_db_prep_save(default, self.connection) File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save prepared=False) File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value value = self.get_prep_value(value) … -
Pickle database independent query in Django
First of all, I know that my question duplicate this question. But I supose it's not the same. I need to save user "search filter". As I understand Django ORM create specific SQL query for different DB. So if I save SQL query I can't migrate on other database with different SQL syntax. Am I wrong? If no, how can I save Django side of query, without accsesing to DB? -
Django 1.9.1 - make migrations can't detect changes
I have Django 1.9.1 installed: >>> django.__version__ '1.9.1' And I had my model defined in main.models: from __future__ import unicode_literals from django.db import models class Collection: name = models.CharField(max_length=1024) desc = models.TextField() snap = models.ImageField() f = models.FileField() def __str__(self): return self.name; And I had already added "main" to INSTALLED_APPS in settings: INSTALLED_APPS = [ 'main', ... # Other Django stuff ] And when I run python manage.py makemigrations I get the following: ➜ python manage.py makemigrations No changes detected I've searched through the internet and it seems like no one has encountered a problem like this... Any help will be greatly appreciated!! Thanks! -
TypeError at /admin/login/ can't multiply sequence by non-int of type 'tuple'
I don't believe it's my code, but something in django? My project works on other machines, but I'm getting a particular error on one: TypeError at /accounts/login/ can't multiply sequence by non-int of type 'tuple' Exception Location: C:\Python34\lib\sitepackages\mysql\connector\django\operations.py in bulk_insert_sql, line 223 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 The method: def bulk_insert_sql(self, fields, num_values): items_sql = "({0})".format(", ".join(["%s"] * len(fields))) return "VALUES " + ", ".join([items_sql] * num_values) Has anyone ran into something like this before? Is it a certain python version, dependencies, or my machine? -
type object 'RadioSelect' has no attribute 'renderer'
I am trying to do a radioselect horizontal align and I am receiving the following error message:type object 'RadioSelect' has no attribute 'renderer' What I am doing wrong? from django.utils.safestring import mark_safe class HorizontalRadioRenderer(forms.RadioSelect.renderer): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) class ApprovalForm(forms.Form): approval = forms.ChoiceField(choices=APPROVAL_CHOICES, initial=0, widget=forms.RadioSelect(renderer=HorizontalRadioRenderer), ) -
sorl thumbnail migrate no effect
I wanna use sorl.thumbnail django app for generating thumbnails in my site. I wanna use sorl.thumbnail django app for generating thumbnails in my site. I followed the guide and I added 'sorl.thumbnail' to INSTALLED_APPS. Also I gonna use the default key-value store, so I need to run python manage.py migrate command, but this doesn't do anything, it doesn't create the required data base table. I also tried python manage.py makemigrations first, still nothing, and tried also python manage.py makemigrations sorl.thumbnail and python manage.py makemigrations sorl.thumbnail. Whats going on? How can I migrate and add the required table in order to use default key-value store? -
Pycharm Django url issues
I have a question related to using Django in Pycharm. I don't know why every time I made a url in urlplattern for my project and this url would not work unless I restart my computer. I did not use virtual environment for my project.