Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create an activity stream in django and angular
I'm working on a project and i'll like to have an activity stream page where recent activities of a users are displayed. Like in my case i have two form models, I'll like other userst o be notified when someone has created a form and also when a form has been approved. Models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime class RequestForm(models.Model): raised_by = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() amount = models.PositiveIntegerField() is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(default=datetime.now) def __str__(self): return 'Raised by: {}'.format(self.raised_by) class VendorForm(models.Model): vendor_name = models.CharField(max_length=500) bank_name = models.CharField(max_length=500) account_details = models.PositiveIntegerField() job_description = models.TextField() quantity = models.PositiveIntegerField() currency = models.CharField(max_length=5) amount_due = models.PositiveIntegerField() delivery_date = models.DateField() current_payment = models.PositiveIntegerField() outstanding_balance = models.PositiveIntegerField(null=True,blank=True) prepared_by = models.ForeignKey(User, on_delete=models.CASCADE) is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(default=datetime.now) def __str__(self): return 'Vendor: {}'.format(self.vendor_name) -
Django set FORM initial values from request.GET with lists
I have a django form that has both CharFields as well ChoiceFields. The form uses HTTP GET. The issue I am having is that request.GET.dict() only contains one value for each key, regardless of if the data is a list or not. I discovered that I can use request.GET.getlist() to get the all the data but it will return a list even if the item is not a list. This is problematic because it causes the CharFields to have the value [u''] What is the recommended way of solving the problem? My current kludge is the following: initial_dict = {k: v for k, v in request.GET.iterlists()} clean_dict = {} for key, value in initial_dict.iteritems(): clean_dict[key] = '' if value[0] == '' else value SellerSearchForm(initial=clean_dict) -
Django reusable limit_choices_to
my app is connected with contacts and addressess - each address entry has its type and category. In several other models I need exact filter on ForeignKey to Address to show in forms for example only manufacturers of chairs (thus filter on two arguments (type : manufacturer / seller / shop, category : chairs / tables / electronics ) Is there possible something like : class Order(models.Model): chair_man = models.ForeignKey(Address, limit_choices_to -> ChairManAddress) # where ChairManAddress is manager for Address model What i need is "reusable" written filter on Address model, which i can use in other models ForeignKeys. Now for testing my filters will be type = 3 and cat = 5, but later on, after filling with real data it will change. I would not like to have to change lots of models fields but only one filter. -
list_editable is super slow on save
I've added a model to the Django admin and I have enabled list_editable for a specific field. When I save the changes, it takes a lot of times and at some point the request timeout. Here the model: class ClientASTM(models.Model): client = ForeignKey2(Client, related_name='astms', verbose_name='client') day = models.DateField(verbose_name='day') last_occurence_date = models.DateField(verbose_name='last occurence', null=True, blank=True) search_term = models.CharField(verbose_name='search term', max_length=255) is_exclude = models.BooleanField(verbose_name='is exclude', default=False) add_datetime = models.DateTimeField(verbose_name='add datetime', auto_now_add=True) mod_datetime = models.DateTimeField(verbose_name='mod datetime', auto_now=True) def __unicode__(self): return u'%s: %s -> %s' % (self.client, self.search_term, self.day) class Meta: ordering = ('-day',) unique_together = (('client', 'day', 'search_term'),) verbose_name = 'Client ASTM' And here my model admin: class ClientASTMAdmin(admin.ModelAdmin): list_editable = ( 'is_exclude', ) list_display = ( 'id', 'day', 'search_term', 'is_exclude' ) It is pretty basic and I do not know what it takes so much time. Do you have any ideas where I could investigate ? Or do you know what I did wrong ? Thank you a lot for your help. -
Django UpdateView doesn't get the values of the object
I have some problems with my UpdateView. I have tried many ways to fix it but failed. So may you can help me: When I click my Update-btn the right html file appears and I can fill out my columns. The Problem is, that there are not the values which should be there! My created object, which I want to update, does not appear. There are just empty columns. My Model: class Patient(models.Model): patientID = models.CharField(max_length=200 , default='Enter PatientID') birth_date = models.DateField(auto_now_add=False, auto_now=False, default='MM/DD/YYYY') gender = models.CharField(max_length=200,choices=Gender_Choice, default='UNDEFINED') height = models.IntegerField( default='[cm]') weight = models.FloatField(default='[kg]') BMI = models.CharField(max_length=200, default='-') def get_absolute_url(self): return reverse('member:detail', kwargs={'pk':self.pk}) def __str__(self): return self.patientID class PatientCreateForm(ModelForm): class Meta: model = Patient fields = ['patientID', 'birth_date', 'gender', 'height', 'weight', 'BMI'] My View: class PatientUpdate(UpdateView): form_class = PatientCreateForm model = Patient template_name_suffix = '_update_form' My URL: # /member/patient/2/ url(r'patient/(?P<pk>[0-9]+)/$', views.PatientUpdate.as_view(), name='patient-update'), My template: patient_update_form.html: <h2>Update patient data</h2> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'member/form-template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success" value="Update">Update</button> </div> </div> </form> html, where I included my UpdateView: <form action="{% url 'member:patient-update' pk=patient.id %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="patient_id" value="{{ patient.id }}"/> <button type="submit" … -
django fancybox does not work
I am new to Django and now developing a website using python django which will show news clip in a table. I am thinking of using fancybox of showing content after the user clicking the news link in the table. I try using django-fancybox 0.1.4. However, after following all the setup, I find the content shows in the same window instead of a fancybox/lightbox. Below is the code. Please advise if you have any idea of where gone wrong. Thanks a lot. settings.py: INSTALLED_APPS = [ 'django_tables2', 'fancybox', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^main/', views.main), url(r'^pr/(?P<pr_id>[0-9]+)$', views.pr_Content), views.py: def pr_Content(request, pr_id): pr_db = db_PRNews.objects.get(pk=pr_id) pr_dbContent = pr_db.Content return render(request, 'remote.html', {'pr_dbContent' : pr_dbContent}) models.py: class SimpleTable(tables.Table): Title = tables.TemplateColumn('<a href="' + r'../pr/'+ '{{record.id}} " class="fancybox">{{record.Title}}</a>', orderable=False) class Meta: model = db_PRNews attrs = {"class": "paleblue"} remote.html: {% extends request.is_ajax|yesno:"fancybox/base.html,pr_fancybox.html" %} {% load i18n %} {% block content_title %}{% trans "REMOTE.HMTL" %}{% endblock %} {% block content %} {{pr_dbContent}} {% endblock %} pr_fancybox.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> … -
Where to initialize the MaxMind IP Database for Django Middleware Use Case
I have the need to test an IPs location during each request. Naturally, this fits nicely with writing a small piece of custom middleware. Given this is python, is it better to initialize the GeoIP2 instance at the module level or should I initialize it per-request? I am using django.contrib.gis.geoip2.GeoIP2 which itself uses: https://github.com/maxmind/GeoIP2-python Specifcially: geoip2.database.Reader() Looking at the source, first for the django module I see that it has some caching options. I have the libmaxminddb C extension installed and according to the docs in the django source MODE_AUTO = 0 is the default which translates it to trying: MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order. Browsing down to the C extension for the database loading: https://github.com/maxmind/MaxMind-DB-Reader-python/blob/master/maxminddb/extension/maxminddb.c It seems to me that the file is not held in memory, which makes perfect sense as that would be an unexpected side effect for anyone using it. That also begs the question: Given that it looks like the mmdb file it's loaded each time GeoIP2 is called/initialized, and since the local database does not change does it make more sense to initialize GeoIP2 at the module level since every request, in my use case, needs it and by initializing at the module … -
Reset limit after request per IP limit exceeded (Django/Apache2)
I have a Django web server and was sending requests to the API via a custom script using the Python requests library. A bug in my script resulted in me continuously resending requests without realising until I got the following error: HTTPSConnectionPool(host='my.addressapi', port=443): Max retries exceeded with url: /jobs/597452/status (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f6e900d3c50>: Failed to establish a new connection: [Errno -2] Name or service not known',)) Now I can no longer send requests to this URL as I keep getting the above error. Is there a way I can reset this limit? The web server is hosted using Apache. I am not sure if Apache or the Django web server is denying my requests. -
Django REST API: Make field read-only for curtain permission level
How make some fields read-only for particular user permission level? There is a Django REST API project. There is an Foo serializer with 2 fields - foo and bar. There are 2 permissions - USER and ADMIN. Serializer is defined as: class FooSerializer(serializers.ModelSerializer): ... class Meta: model = FooModel fields = ['foo', 'bar'] How does one makes sure 'bar' field is read-only for USER and writable for ADMIN? I would use smth like: class FooSerializer(serializers.ModelSerializer): ... class Meta: model = FooModel fields = ['foo', 'bar'] read_only_fields = ['bar'] But how to make it conditional (depending on permission)? -
Converting date to string in template
I want to convert data to string in template (To simplify the url) For this i do following : CSV for current range payments but getting NoReverseMatch at /payment/list/range/ Reverse for 'export_payment_range_csv' with arguments '()' and keyword arguments '{u'start_date': '', u'end_date': ''}' not found. 2 pattern(s) tried: ['condition/export/range/csv/(?P\d+)/(?P\d+)/$', 'payment/export/range/csv/(?P\d+)/(?P\d+)/$'] What I do wrong? -
How to force factory boy to create a new instance?
I'm currently writing unit tests for a Django project (https://github.com/aledejesus/sudoku_solver). I'm using factory_boy to create instances of my models. I have 2 test cases, SudokuPuzzleTestCase and PuzzleCellTestCase. The problem is that whenever I run the 2 test cases separately they pass but fail when ran together. After some debugging I came to the conclusion that the changes made to the instances created through factory_boy in the first test case persisted in the second test case. I noticed that if I called SudokuPuzzleFactory.create() twice the first time an instance was created but the second time the create method returned the instance created the first time I called it. According to factory_boy source code this is expected behavior (https://github.com/FactoryBoy/factory_boy/blob/master/factory/django.py#L174). I was trying to override the _create method so that it creates a new instance even if one with the same attributes is already created. Even when I overrode the _create method in both of my factories I keep on getting the same error. Am I missing something? Is there a better way to solve this problem? Models: https://github.com/aledejesus/sudoku_solver/blob/is_16/solver/models.py Factories: https://github.com/aledejesus/sudoku_solver/blob/is_16/solver/factories.py Tests: https://github.com/aledejesus/sudoku_solver/blob/is_16/solver/tests.py -
django-contact-form Site model error
Got the following error while trying to use django-contact-form. I installed it using pip, created the templates, setup the email, wrote the url(r'^contact/', include('contact_form.urls')) and got the following error: Unhandled exception in thread started by <function check_errors.locals>.wrapper at 0x00000000048107B8> File "C:\Users\Caio\Documents\Projects\JCC\venv\lib\site-packages\django\db\models\base.py", line 113, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. -
How to return customized response to api /rest-auth/login/ in Django Framework
Here is sample code from where i want to return customized response as this class will be called at the time of login. class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): try: print("Do Something") except exceptions.AuthenticationFailed as e: print(e) -
What's the best way to pass model data between views?
I have a basic diary application that has two views: Add and Edit view. When user hits 'Add' button on Add view, the data is saved into database and simple message is shown. When user hits 'Update' button on Edit View, the data is updated and a last update stamp is added. So far these views run independently. The Edit View by default loads the last saved entry and allows for that to be updated. I want to update it so that Upon successful entry of new event on Add View, it transitions to the Edit View to allow the user to Edit and Update if they want to. How do I link the views together and pass the relevant data to Edit View to know which entry to fetch for edit? Also I would like to be able to use the Edit View independently to fetch a specified diary entry. The code for Add and Edit View as they are, are displayed below: def addEntry(request): entryForm = None if request.method == "POST": entryForm = EntryForm(request.POST) if entryForm.is_valid(): entryForm.save(commit = True) request.method = "GET" return entrySubmitted("Entry has been submitted") else: logger.info(entryForm.errors) else: # Set up view with new entry form … -
Connect Profile model to remote user (custom auth backend)
I am in the process of writing a custom authentication backend to authenticate against a RESTful API. I don't know how I would connect a Profile model (that would contain information that isn't in the remote database) to those users in a way that is immune to changes in usernames, etc. For example, if I wanted to have a 'Bio' field for those users, then I would normally do this: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True) def __str__(self): return self.user.email Is this possible with a custom API-based authentication backend? If so, what would I put in the OneToOneField that connects it to the remote users? Would I just have to ensure the authentication backend updates a local database of users and then the Profile model would connect to that? That is how I was going to try this but I figured I would query the community on how this is done elsewhere. -
Django: convert string to HTML is possible?
I pass string variable to django template as context variable: my_var = "<h1> hihih </h1>" In my template, I use {{ my_var }} and want to show it as HTML, not just <h1> hihih </h1>. Is it possible? (I don't need any other kind solution...) -
Django redis LPUSH / RPUSH
I am using the django-redis backend and the django.core.cache.cache module. The django cache module does not seem to support proper functionality of pushing to lists and manipulating certain data structures. The implied implementation used to update a list in the django cache module: my_list = cache.get('my_list') my_list.append('my value') cache.set('my_list', my_list) This approach is not efficient because the entire list is being loaded into the application server's memory. Redis has support for the LPUSH / RPUSH commands to dynamically update a list. However, it doesn't look like these methods are available in the django cache module. The official python redis client seems to implement these methods. Is there any reason why django wouldn't offer this implementation? I'm asking out of my curiosity. Possibly I missed some details? -
django charfield returns object instead of string
I am trying to get city from model 'Agents', but is showing u'Cities object' instead of the city value, ¿what is the reason for this? ¿How i can show the value of the field? Example code Agents.objects.get(pk=1).city Models class MyUserManager(BaseUserManager): def create_user(self, email1=None, password=None, **extra_fields): if not email1: raise ValueError('Users must have an email address') user = self.model( email1=self.normalize_email(email1), **extra_fields ) user.save(using=self._db) return user def create_superuser(self, email1, password): user = self.create_user( email1=email1, password=password, ) user.is_admin = True user.save(using=self._db) return user class Agents(AbstractBaseUser): oldkey = models.CharField(max_length=32, blank=True, null=True) is_main_user = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) lastname = models.CharField(max_length=45, blank=True, null=True) email1 = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) email2 = models.CharField(max_length=100, blank=True, null=True) country = models.ForeignKey( 'buildings.Countries', models.DO_NOTHING, db_column='country', blank=True, null=True) username = models.CharField( max_length=30, blank=True, null=True, unique=True) image = models.CharField(max_length=80, blank=True, null=True) num_access = models.IntegerField(blank=True, null=True) phone1 = models.CharField(max_length=20, blank=True, null=True) phone2 = models.CharField(max_length=20, blank=True, null=True) phone3 = models.CharField(max_length=20, blank=True, null=True) whatsapp = models.CharField(max_length=20, blank=True, null=True) bbm_pin = models.CharField(max_length=20, blank=True, null=True) permissions = models.CharField(max_length=10, blank=True, null=True) fb_profile_id = models.CharField(max_length=30, blank=True, null=True) fb_access_token = models.TextField(blank=True, null=True) clients = models.ForeignKey( 'Clients', models.DO_NOTHING, blank=True, null=True) last_login_time = models.IntegerField(blank=True, null=True) birthday = models.DateField(blank=True, null=True) workexperience = models.CharField(max_length=140, blank=True, null=True) state … -
URL Error in Django,Page not found 404
This is my views.py from django.http import Http404 from django.shortcuts import render from .models import Album def index(request): all_albums = Album.objects.all() return render(request, 'music/index.html', {'all_albums': all_albums}) def detail(request, album_id): try: album = Album.objects.get(pk=album_id) except Album.DoesNotExist: raise Http404("Album does not exist") return render(request, '/music/detail.html', {'album': album}) This is my music\urls.py from django.conf.urls import url from . import views urlpatterns = ( url(r'^$', views.index, name='index'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), ) When i used to run this code,i am getting the error as mentioned in the image.Help me with this error inorder to move forward. Thks -
Setting up Django model with built in User class
I am trying to figure out the best way to design my Django models. In my following company model. I want the ability to say that a company can have one or more company contacts and that company contact can have a user profile or not. How can I achieve this? Am I on the right track? from django.db import models from django.contrib.auth.models import User # Create your models here. class Company(models.Model): name = models.CharField(max_length=120) account_name = models.CharField(max_length=10, default="") sales_rep = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_sales", default="") csr = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_csr", default="") company_contact = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_contact", default="") -
How do you extract a url from a string using python/django?
string = "http://www.youtube.com/watchv=ClkQA2Lb_iE.......https://www.youtube.com/watch?v=ClkQA2Lb_iE, eeeeeee.www.youtube.com/watch?v=ClkQA2Lb_iE/vvvvvvvvvvv---websitename.com:1234/dir/file.txt" How could I extract http://www.youtube.com,https://www.youtube.com,www.youtube.com,websitename.com -
Can be create users and products filtered by location in Saleor
Is there a way to assign users by location? So that they can only edit the products in a location the users who have registered them? -
How to pass Date Range Picker start and end value to django view.py
I am using a Date Range Picker (http://www.daterangepicker.com/) and I would like to pass selected start and end date to django view.py so I can generate report between this two dates. This is my html: {% extends "Base.html" %} {% load crispy_forms_tags %} {% block head_title %} WEB RT | Poročila {% endblock head_title %} {% block content %} <form method="POST" action="report/"> {% csrf_token %} {{form.as_p}} <button type="submit" id="send">Izpis poročila</button> <div class="col-md-4"> <div> <div id="reportrange" name = "date" class="pull-right" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%"/> <i class="glyphicon glyphicon-calendar fa fa-calendar"></i>&nbsp; <span></span> <b class="caret"></b> </div> <script type="text/javascript"> $(function() { var start = moment().subtract(29, 'days'); var end = moment(); function cb(start, end) { $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); } $('#reportrange').daterangepicker({ startDate: start, endDate: end, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }, cb); cb(start, end); }); </script> </div> </form> {% endblock content %} This is my view.py def report (request): if request.method == 'POST': date_start = request.POST['start'] date_end = request.POST['end'] form = … -
How do I use the pusher(real time framework) with django and angular js
I'm currently working on a small scale app using angular and django. Like an office environment where you create forms and submit for approval, the app does the same. Now I want to add a real-time notification feel to it whereby once a form is submitted the user to approve receives a notification and once the form is approved I also get a notification. I've checked out the pusher tutorials but I don't seem to understand it. Here's my models.py from django.db import models from django.contrib.auth.models import User from datetime import datetime class RequestForm(models.Model): raised_by = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() amount = models.PositiveIntegerField() is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(default=datetime.now) def __str__(self): return 'Raised by: {}'.format(self.raised_by) class VendorForm(models.Model): vendor_name = models.CharField(max_length=500) bank_name = models.CharField(max_length=500) account_details = models.PositiveIntegerField() job_description = models.TextField() quantity = models.PositiveIntegerField() currency = models.CharField(max_length=5) amount_due = models.PositiveIntegerField() delivery_date = models.DateField() current_payment = models.PositiveIntegerField() outstanding_balance = models.PositiveIntegerField(null=True,blank=True) prepared_by = models.ForeignKey(User, on_delete=models.CASCADE) is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(default=datetime.now) def __str__(self): return 'Vendor: {}'.format(self.vendor_name) views.py from rest_framework import permissions from rest_framework.viewsets import ModelViewSet from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_protect from .models import RequestForm, VendorForm from .serializers import VendorSerializer, RequestSerializer class RequestViewSet(ModelViewSet): queryset = RequestForm.objects.all() serializer_class = ImprestSerializer permission_classes = … -
Django doesn't email reporting an internal server error (HTTP status code 500)
I could send mail using the following code E:\Python\django-test\LYYDownloaderServer>python manage.py shell Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.core.mail import send_mail >>> >>> send_mail( ... 'Subject here', ... 'Here is the message.', ... 'redstone-cold@163.com', ... ['2281570025@qq.com'], ... fail_silently=False, ... ) 1 >>> but Django doesn't email reporting an internal server error (HTTP status code 500) what's the problem? please help fix the problem settings.py """ Django settings for LYYDownloaderServer project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os ADMINS = [('Philip', 'r234327894@163.com'), ('Philip2', '768799875@qq.com')] EMAIL_HOST = 'smtp.163.com' # 'localhost'#'smtp.139.com' # EMAIL_PORT = 25 # EMAIL_USE_TLS = True EMAIL_HOST_USER = 'r234327894@163.com' # '13529123633@139.com' EMAIL_HOST_PASSWORD = '******' # DEFAULT_FROM_EMAIL = 'r234327894@163.com' # 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.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 's4(z8qzt$=x(2t(ok5bb58_!u==+x97t0vpa=*8bb_68baekkh' # SECURITY WARNING: don't run with debug turned on in production! DEBUG …