Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add CSS within an app in wagtail
Wait! Before you mark this as a duplicate read on! I am using Wagtail based on Django. I have an app 'blog' in wagtail. I want to add a custom CSS stylesheet for one of my templates. Django docs say to just add stuff in your settings file but I don't have one as an app? Please help, I understand that it involves static files, just can't figure out how to make it work! Thanks! -
Django Tables2 - Making tables for each model object on one page
I believe my question will be better explained once I give the relevant code: models.py class Student(models.Model): student_id = models.CharField(max_length=128, unique=True, null=True, blank=True) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) ssn = USSocialSecurityNumberField(null=False) gender = models.CharField(max_length=128, choices=GENDER_CHOICES) dob = models.DateField(auto_now=False, auto_now_add=False, db_column="date of birth") address = models.CharField(max_length=128) city = models.CharField(max_length=128) state = USStateField(choices=STATE_CHOICES, default='NJ') zipcode = USZipCodeField(blank=True) country = CountryField(default='US', blank=True) primary_phone = models.CharField(max_length=128) secondary_phone = models.CharField(max_length=128) email = models.EmailField(max_length=254, validators=[validate_email]) background = models.CharField(max_length=128, choices=BACKGROUND_CHOICES) location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') workforce = models.CharField(max_length=128, choices=WORKFORCE_CHOICES, default='--') source = models.CharField(max_length=128, choices=SOURCE_CHOICES, default='individual') refer_by = models.CharField(max_length=128, choices=REFER_BY_CHOICES, default='no refer') last_status = models.CharField(max_length=128, choices=LAST_STATUS_CHOICES, default='followup') newsletter = models.BooleanField() notes = models.TextField() created_by = models.CharField(max_length=32, null=True, blank=True) changed_by = models.CharField(max_length=32, null=True, blank=True) created_at = models.DateTimeField(null=True, auto_now_add=True) updated_at = models.DateTimeField(null=True, auto_now=True) class StudentCourse(models.Model): student = models.ForeignKey(Student) course = models.ForeignKey(Course) class StudentEmployment(models.Model): student = models.ForeignKey(Student) company = models.CharField(max_length=128, blank=True) title = models.CharField(max_length=128, blank=True) class StudentCounselor(models.Model): student = models.ForeignKey(Student) counselor = models.ForeignKey(Counselor) tables.py class StudentListTable(tables.Table): name = tables.TemplateColumn('''{{ record.first_name }} {{ record.last_name }}''', verbose_name=u'Name') manage = tables.TemplateColumn('''<a href="/students/update_student/{{ record.id }}">Update</a> / <a href="/students/delete_student/{{ record.id }}" onclick="return confirm('Are you sure you want to delete this?')">Delete</a>''') assign = tables.TemplateColumn('''<a href="/students/id={{ record.id }}/add_studentcourse">Courses</a> / <a href="/students/id={{ record.student_id }}/add_studentemployment">Employment</a> / <a href="/students/id={{ record.id … -
Weblate installation issues
I've been having issues with installing Weblate onto my AWS ubuntu instance. I've tried following the quickstart where I installed all dependencies, changed settings.py, and set the server up and everything else. I've also did a sanity check to ensure I can at least run Weblate using django's builtin server and that works perfectly. The issue comes from setting up apache and mod_wsgi. Once I take the apache.conf and load that file, then go to my site, I can a 500 Internal Error where the error log says "ImportError: No module named django". I've ensured that django is installed, so not sure how to debug this. Following this, I made a second instance and tried to follow the virtualenv instructions. Again, set everything up and did a sanity check to see if django runs at all, and same result, everything runs on django builtin server. Next, I decided to again go with apache and wsgi and this time I get an OSError where it says my DATA_DIR is not writable. The data directory is located in site-packages directory, so unsure if that's the correct place to point, but this was default in settings.py. -
SignatureDoesNotMatch Error when uploading mp3/m4a files to S3 but all other files upload
I am using react-s3-uploader to upload files to S3 bucket. All file types and file sizes work exept mp3 and m4a files. Large mp4 files upload no proble, images, text, etc. I even changed the file extension of the mp3 to mp4 and it uploaded. However every time I try to upload an mp4 or m4a S3 returns SignatureDoesNotMatch error: <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <AWSAccessKeyId>******</AWSAccessKeyId> <StringToSign>PUT audio/mp3 1503508664 x-amz-acl:private /tl2/generic_video/4/1-05IGuessHedRatherBeInColorado.mp3</StringToSign> <SignatureProvided>dt1lf51Z/L/4pvkj3dC9ybOTTRw=</SignatureProvided> <StringToSignBytes>50 55 54 0a 0a 61 75 64 69 6f 2f 6d 70 33 0a 31 35 30 33 35 30 38 36 36 34 0a 78 2d 61 6d 7a 2d 61 63 6c 3a 70 72 69 76 61 74 65 0a 2f 74 6c 32 2f 67 65 6e 65 72 69 63 5f 76 69 64 65 6f 2f 34 2f 31 2d 30 35 49 47 75 65 73 73 48 65 64 52 61 74 68 65 72 42 65 49 6e 43 6f 6c 6f 72 61 64 6f 2e 6d 70 33</StringToSignBytes> <RequestId>FDA3BA86E19BEA87</RequestId> <HostId>***</HostId> </Error> Below are the code snippets for the client and server. … -
Running Tests in Parallel with Django
In my Django project I now have 55 tests. It's taking quite a long time to run them so I tried running them in parallel. This failed at first but then I installed tblib and the tests started running. Unfortunately the tests are now failing for reasons I haven't yet determined. It might be because initial calls need to be placed to a remote server to populate the test databases; before there was one, now there appear to be four. My question is this: Are there any "gotchas" I should be aware of when attempting to run parallel tests with Django? Robert -
Django loads CSS very slow and where should I insert {% static 'Layout.css' %.}
I am working on a web-app using Django and everything is going well but there are two problems that I have been struggling with for the past week: Problem 1: Within my project I have an app called User and it has the following structure: User >templates >User >Layout.html >Home.html >static >css >User >Layout.css >Home.css I want to have the same header and left side menu across all my pages and here is how I went about it. Layout.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'User/css/Layout.css' %}"> {% block head %} {% block title %} {% endblock %} {% block references %} {% endblock %} {% endblock %} </head> <body> <header class="uppermenu"> </header> <div class="leftsidemenu"> </div> <div class="content"> {% block content %} {% endblock %} </div> </body> </html> Home.html {% extends "User/Layout.html" %} {% load static %} {% block head %} {% block title %} <title>Home</title> {% endblock %} {% block references %} <link rel="stylesheet" href="{% static 'User/css/Home.css' %}"> {% endblock %} {% endblock %} {% block content %} <!--Each page is going to have different content but the left side menu and the header should remain the same --> {% endblock %} When … -
Django Rest - Error when creating a custom response message
I want to implement an email verification and the way I have got it working seems "hacky" but it seems to work good. I've created a custom response in the return portion of the function, but I keep getting the following error: The response content must be rendered before it can be iterated over. The process is the standard someone registers and when I go to save the User model I have a send_mail() function that sends out the email with a verification key. The user clicks the link and it passes the key like this: /api/account/verify/849c40665175e56709855cc7aec2b16c05a4d977b3b083790334c6bc01f6e522 In the view you can see where I pull the key out and process everything. I'm guessing the error is because I'm using Response() in get_queryset(), but I'm not sure. If not, how do I create a custom response message? Versions Python==2.7.10 Django==1.11.4 djangorestframework==3.6.3 Model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), null=False, unique=True) first_name = models.TextField(_('first name'), null=False) last_name = models.TextField(_('last name'), null=False) is_active = models.BooleanField(_('active'), default=False) is_admin = models.BooleanField(_('admin'), default=False) created_on = models.DateTimeField(_('create on'), auto_now_add=True) updated_on = models.DateTimeField(_('updated on'), auto_now=True) is_staff = models.BooleanField(_('staff'), default=False) activation_key = models.CharField(_('email validation key'), default='', max_length=256) View class ActivateViewSet(generics.ListAPIView): queryset = User.objects serializer_class = UserSerializer serializer … -
How to force Django Admin to save the inline?
I have an app who uses Django Inline Admin. from django.db import models class MyClass(models.Model): field1 = models.CharField(max_length=128) fieldN = models.IntegerField() class MyInlineClass(models.Model): field1 = models.CharField(max_length=128) field2 = models.ForeignKey(MyClass) fieldN = models.IntegerField() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self.field2: self.field1 = self.field2.field1 return BaseModel.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields) For reasons beyond my control, the fieldN is repeated in MyClass and in MyInlineClass. So the user has to change the fieldN on MyClass and on eachone of the inlines. I want to save fieldN on the inline when changing fieldN on my admin class. from django.contrib import admin class MyInlineClassInline(admin.TabularInline): model = MyInlineClass fields = ['field2'] class MyClassAdmin(admin.ModelAdmin): inlines = [MyInlineClassInline,] If I override the MyClass save method, how could I force to call MyInlineClass save method also? Any thoughts? -
Django, in many to many relationship within the self class, how do I reference each other in terms of ORM?
class User(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() gender = models.IntegerField() email = models.CharField(max_length=100) password = models.CharField(max_length=255) following = models.ManyToManyField("self", related_name='followers') objects = UserManager() def __repr__(self): return "User: {0}".format(self.name) In my model, User, users can follow and followed by each other. I can find who the user is following by this: user1 = User.objects.get(id=1) following = user1.following.all() However, I can't figure out how to find whom the user is followed by. I tried: user1.followers.all() since it is the related_name in the following field in my model. Can anybody please teach me how to do this? Thank you very much. -
ListView to return a rating for each item in the list, taken from ForeignKeys
In brief, I want to display a list of teachers and their corresponding rating using ListView. Currently, I have models.py: class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher') availability = models.BooleanField(default=False) class Review(models.Model): teacher = models.ForeignKey(Teacher) student = models.OneToOneField(Student, on_delete=models.PROTECT, related_name='Student') star = models.IntegerField(default=5) body = models.TextField() In my list view, I define the query_set function to be: class IndexView(ListView): def get_queryset(self): """Return the last five published teachers.""" return Teacher.objects.all()[:5] Now I have the object teacher_list which I can use in the template. I know how to get an average rating for an individual rating using: Review.objects.filter(teacher_id=self.kwargs['pk']).aggregate(Avg('star')) Now I just need to change is so that I don't specify the value of teacher_id and include it in the teacher_list query set. So every teacher in teacher_list has teacher.rating attribute. This Django tutorial suggests that I can access the related models directly using the teacher object. So for teacher in teacher_list, I should be able to see all reviews using teacher.star_set.all() . I will then simply find the average of this value, and display it somehow. -
How do I filter values in Django CreateView, UpdateView
I am trying to use CreateView and UpdateView to modify records. My problem is that the ForeignKey dropdown lists values (Psa.number) for all companies instead only those of the company to which the user belongs. class Psa(models.Model): owner = models.ForeignKey(Employer) number = models.PositiveIntegerField(unique=True... type = models.CharField(max_length=6 ... class Employer(models.Model): employer_name = models.CharField(max_length=100, unique=True) The form: class PsaCreateForm(forms.ModelForm): class Meta: model = Psa fields = [ 'number', 'type', ] What is the best way to solve this? I've got several other conditions that use the same company foreignkey relationship so is there a way to create a method on the model that I can reuse? -
Python split video file into smaller parts
I am stuck with my project(web application using Python-Django) on converting a large file(say 1GB) to small parts using python.I could create the large file into smaller parts,but the problem is only the part 1 gets played and rest of the files wont open. I understood i need to specify the video information before the video data but i dont know how. Below is my code and someone help me how i could split the the large file into smaller ones. [N:B] I need to split the video from the django views when the upload is completed `def video_segments(video): loc = settings.MEDIA_ROOT + '/' + format(video.video_file) filetype = format(video.video_file).split(".") data = None i = 0 start_index = 0 end_index = 1024000 file = Path(loc) size = file.stat().st_size file = open(loc, "rb") while end_index < size: i=i+1 file.seek(start_index) bytes = file.read(end_index-start_index) newfile = open(settings.MEDIA_ROOT+"/"+filetype[0]+format(i)+"."+filetype[1],"wb") newfile.write(bytes) start_index = end_index + 1 end_index = end_index + 1024000 ` -
Django Rest Framework. For what is really for?
I'm a little confused about the Django Rest Framework. I know is used to construct APIs but I'm wondering if it can be used in combination with CBV as a replacement for Ajax calls(for example delete,updates). If yes, some tutorials/links will help me a lot. I'm just starting to learn about it, so I'm sorry if is a stupid question, -
Django TemplateDoesNotExist
I deployed my website on the server Ubuntu 16.04.3 x64 I don't know the main template list.html it doesn't work other templates are working normally. templates I checked the access permissions files They are the same Permissions Settings looks like this """ Django settings for INZ project. Generated by 'django-admin startproject' using Django 1.10.4. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#wx61%!ioz(yba#e=t7jh-*&(!l#kri=^y%ik(x4m3j8oix+hq' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['46.101.116.26'] EMAIL_HOST ='smtp.gmail.com' EMAIL_HOST_USER ='luke.rudzinski@gmail.com' EMAIL_HOST_PASSWORD = '#####' EMAIL_PORT = 587 EMAIL_USE_TLS = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'games' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'INZ.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'INZ.wsgi.application' # Database … -
Segregate po files in django
I need to translate around 7000+ city names for my website, but I need them to be in a separate po file. We often need to get things translated, and we are charged per line - we do not want to send the extra 28,000 lines created by the cities to our translators. Currently, we have: locale LANG LC_MESSAGES django.mo django.po djangojs.mo djangojs.po I'd like to add another for cities, something like this: locale LANG LC_MESSAGES django.mo django.po django_cities.mo django_cities.po djangojs.mo djangojs.po However, when I try doing this with makemessages, I get the CommandError: CommandError: currently makemessages only supports domains 'django' and 'djangojs' I've been trying to find a work around that doesn't include: Having to remove all the cities from the po before sending it to the translators Manually separating the cities in the po file after every makemessages/compilemessages. -
Django: use slugify for detail url
I want to use slugs in my details urls but when I want to acces to a url like this: localhost:8000/movie-1 Send me this error Value Error: invalid literal for int() with base 10: 'pelicula' Here is my model: from django.utils.text import slugify class Movie(models.Model): name = models.CharField(verbose_name='nombre', max_length=250) @property def slug(self): return '{}'.format(slugify(self.name, allow_unicode=True)) My url: url( regex=r'^(?P<slug>[\w-]+)/$', view=views.DetailMovie.as_view(), name='movie' ), And finally my view: class DetailMovie(DetailView): model = Movie pk_url_kwarg = "slug" context_object_name = "movie" template_name = "detail_movie.html" Thanks a lot for your help! -
How to find out, what python process\code does so much time (this happens ~ once a month and already works 92 hours)?
I have a Django project with uWSGI which runs everyday job: cron2 = minute=00,hour=1,unique=1 ./manage.py catalogue_create db --update_all_indexes=True In my case catalogue_create db downloads json file and updates products' prices, indexes and other things. Usually it takes about 1 hour. Sometimes (about once a month or even once a two months) the process can not be finished. In htop (I use Ubuntu Server) I see the next: PID USER PRI NI VIRT RES SHR S CPU% MEM% TIME+ 31 46.6% 92h22:46 Usualy I simply reboot the server but this time I want to find out, how is it possible to see, what this process (or the script) does? Why does it take so long and can not be finished. -
python manage.py runserver command results in access denied
Hi I am new to django and python both. When I type this command python manage.py runserver from mysite directory (as told in this tutorial) the command prompt shows ACCESS IS DENIED. I have tried using port no.s 8000 and 8080 in the commmand. Please Help. -
pyral accessing customfield .attributes values from CA Agile Central
I'm super new in development in general. I'm currently building a webapp that get data from Rally/CA Agile Central and put them in a neat table. My code: response = rally.get('UserStory', fetch = True, query=query_criteria) response_defect = rally.get('Defect', fetch = True, query=query_criteria) story_list = [] if not response.errors: for story in response: #print (story.details()) a_story={} #a_story['State'] = story.State.Name #if story.State else "Backlog" a_story['State']=story.BusOpsKanban if story.BusOpsKanban else "unassigned" #a_story['Status']=Story.Status if story.Status else "unassigned" a_story['id'] = story.FormattedID a_story['name'] = story.Name a_story['Opened']=(datetime.strptime(story.CreationDate, '%Y-%m-%dT%H:%M:%S.%fZ').strftime('%Y-%d-%b')) a_story['Requester']= story.Owner.Name if story.Owner else "unassigned" a_story['Blocked']= story.Blocked a_story['Service']=story.c_ServiceNowID Blockquote My issue is to get access to the value of the linkid of my customfield (c_ServiceNowID). When I run a Dict = I see that I have LinkID attributes but when I type story.c_ServiceNowID.LinkID, I receive an error message telling me there is no such attributes.... How do I access this value using python ? Thank you -
Reverse for 'detail' with keyword arguments '{'id': 5}' not found. 1 pattern(s) tried: ['posts/(?P<slug>[\\w-]+)/$']
I'm super stuck with NoReverseMatch at /posts/ error. Maybe I am overlooking something small or maybe this issue is much bigger than where I am digging. http://imgur.com/nlyMi9V Error message when models.py is like this: def get_absolute_url(self): #return reverse("detail", kwargs={ "slug": self.slug }) return reverse("posts:detail", kwargs={ "slug": self.slug }) http://imgur.com/a/RilrB Error message when models.py is like this: def get_absolute_url(self): return reverse("detail", kwargs={ "slug": self.slug }) #return reverse("posts:detail", kwargs={ "slug": self.slug }) models.py #from _future_ import __unicode__literals from django.db import models from django.core.urlresolvers import reverse from django.db.models.signals import pre_save from django.utils.text import slugify # Create your models here. # MVC Models Views Controller def upload_location(instance, filename): # filebase, extension = filename.spilt(".") # return "%s/%s.%s" %(instance.id, instance.id, filename) return "%s/%s" %(instance.id, filename) class Post(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): #return reverse("detail", kwargs={ "slug": self.slug }) return reverse("posts:detail", kwargs={ "slug": self.slug }) class Meta: ordering = ["-timestamp", "-updated"] def create_slug(instance, new_slug=None): slug = slugify(instance.title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if … -
connect to Custom websockets app in django chat application
i have a chatting application in my Django website project using webfaction server, so i followed the channels multichat example but when i try to connect and create the websockets handshake i got this error: [Error] WebSocket connection to 'ws://gadgetron.store/Pchat/' failed: Unexpected response code: 404 PS: i have created a Custom websockets app (listening on port) using the control panel , and the support-team said to me that i need to make my application listen to the websockets app port....but i don' know how ?! -
how to access item by ForeignKey lookup field instead of pk?
In django rest framework(DRF) I want access item by Foreign Key lookup field instead of pk url:\investment\< member >\ class InvestmentListViewSet(viewsets.ModelViewSet): queryset = Investment.objects.all() serializer_class = InvestmentSerializer lookup_field = 'member' but have a error: investment.models.MultipleObjectsReturned: get() returned more than one Investment -- it returned 6! This is my model class Investment(models.Model): member = models.ForeignKey(Member) project = models.ForeignKey(Project) time = models.DateField(default=datetime.now) how to use Foreign Key access items? -
How rewrite query in Django ORM?
Please Help rewrite to Django ORM SELECT * FROM T WHERE REPLACE(T.field, '-', ' ') = REPLACE(VALUE,'-', ' ') -
Django AllAuth - How to manually send a reset-password email?
In my application I am using Django Allauth. I don't have any registration form for users. The admin is going to register users by uploading an excel file that contains user info. I have done all of this and users are saved in the user table by auto generating passwords. After I upload user lists and save them in database, I want to send a reset password email to each user. In allauth to reset password you first need to go to reset page account/password/reset/ and type your email. then an email is send which directs you to change your password account/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/ Is it possible to send the email directly within the app? The url contains a key that I don't know how to generate!! Or is there any better way to do that? -
How to inform users that delete request as been sent to admin in Django
So i am creating a Django forum site for a school project. I have created a question and comment model. I want to add this feature but do not know how to go about it : If the user clicks the delete button for a comment, the admin should receive a request(message of some sort) to delete the comment and a popup or message should tell the user that a request for deleting the comment as been received by the admin. I want this feature because i do not want the users to delete comments that might be important in the future but if they wrote irrelevant things the admin can then delete the comment