Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit Django users to one single group
I'm rather surprised that this hasn't been asked before, but I need to limit my Users in Django to only belong to one single Group. How would I do this? Thanks in advance. -
Strange URL in HTTP_HOST
I have received an error report from my Django-based site, with a strangely looking HTTP_HOST: https://810067644/. The IP location is in China, which hints in the direction of a hacking attempt. But I have no idea what actual activity this indicates. It's not a login attempt via website login page, it's not a login attempt against the server SSH either. Does anyone have a clue what it could mean? Any suggestions what aspects of protection to check for this event? I've a DigitalOcean droplet with Ubuntu 16.04 running Django 1.11. Only HTTP and HTTPS ports are open, and password-based ssh login is disabled. The site is only accessible via HTTPS. Invalid HTTP_HOST header: '810067644'. You may need to add '810067644' to ALLOWED_HOSTS. Report at / Invalid HTTP_HOST header: '810067644'. You may need to add '810067644' to ALLOWED_HOSTS. Request Method: GET Request URL: https://810067644/ Django Version: 1.11.1 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.2 Python Path: ['.', '', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Fri, 19 May 2017 10:01:30 +0000 Installed Applications: ['photos.apps.PhotosConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'auditlog', 'axes'] Installed 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', 'auditlog.middleware.AuditlogMiddleware'] Request information: USER: [unable to retrieve the current … -
How to count and return the objects related to a table to a model field
I'd like to know how to count the number of Students related to a certain ClassRoom, and to place the current quantity to a field so whenever I add a student to a ClassRoom I can know the current number of students in it. class Student(models.Model): ClassRoom = models.ForeignKey(ClassRoom) class ClassRoom(models.Mode): qtt_current_students = -
How to load SHPAML template preprocessor
Unfortunately, SHPAML's documentation is severely out of date. I suspect this is a case where it might work, if only I understood django better. Here's what I've managed to work out so far: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_DIR, 'templates'), ], 'APP_DIRS': False, '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', ], 'loaders': [ #('shpaml_loader.filesystem') ('shpaml.Loader', ('django.template.loaders.filesystem.Loader',) ), 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'debug': True, }, }, ] This results in the error "shpaml" does not define a "Loader" attribute/class. I understand from here that the solution may involve using django-shpaml-template-loader but how to do that isn't clear at all. -
Filtering nested resources Django REST Framework
At the begining I want to say that I found partial answer for my question(How can I apply a filter to a nested resource in Django REST framework?), but its not cover my problem in 100%. I have nested 3 models: - Category -- Subcategory ---- Subsubcategory I need get all Categories filtering over subsubcategory but I need also that subsubcategory will be filtered. Ex. /categories?sub__subsub__id=100 It need returned values: [{id:1, sub: [{ id:10 sub{ id: 100 }] }] }] but it return [{id:1, sub: [{ id:10 sub{ id: 100 }, id:11 sub{ id: 102 }] }] }] So it's only filtering on first level of nesting. I want to that applied filter will be applied for all nested models. -
Multiple images in django form with multiupload
I need to add multiple images in django form to one model. I did a research and for form outside of django I try to setup django-multiupload. My models.py: class Profile(models.Model): ... ... first = models.ImageField("first", upload_to='first') second = models.ImageField("second", upload_to='second') ... In forms.py: class AddForm(forms.ModelForm): first = MultiImageField(min_num=1, max_num=20) second = MultiImageField(min_num=1, max_num=4) In views.py: class UploadView(FormView): template_name = 'finder/submit.html' form_class = AddForm success_url = '/' def form_valid(self, form): for each in form.cleaned_data['first']: Profile.objects.create(first=each) for each in form.cleaned_data['second']: Profile.objects.create(second=each) return super(UploadView, self).form_valid(form) And on submitting form this form creates multiple Profile objects with only first/second field filled. How can I create only one model with remaining fields (other than first/second) and with multiple first/second fields? It was my function-based view before adding multiupload but I couldn't make it work, maybe it's easier to change it somehow? def add_form(request, *args, **kwargs): if request.method == "POST": form = AddForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.save() return redirect('/', pk=profile.pk) else: form = AddForm() return render(request, 'finder/submit.html', {'form': form}) -
Get filename of diferrents models
i need some help in a situation with in using django: I have 5 models , when do a upload file in format pdf Here an example: class News(BaseCadastroModel, ProfilesBase, SEORelation): title = models.CharField(verbose_name=u'Título', max_length=255, null=False, blank=False, default='') short_title = models.CharField(verbose_name=u'Título curto', max_length=30, null=False, blank=False, default='') short_description = models.TextField(u"Descrição Curta", blank=True, null=True) content = models.TextField(verbose_name=u'Notícia', null=False, blank=False) creation_date = models.DateTimeField(verbose_name=u'Data de criação', null=False, blank=False, auto_now_add=True) pdf = ContentTypeRestrictedFileField(verbose_name=u'upload de arquivos', upload_to=u'cadastro/news/', content_types=['application/pdf'], max_upload_size=10485760, null=True) I a need to create a field which receives the name of the file pdf. My model.py: class ContactDownload(BaseCRMModel): name = models.CharField(verbose_name=u'Nome',max_length=256) email = models.CharField(verbose_name=u'Email',max_length=256) origem = models.CharField(verbose_name=u'Origem', max_length=256) created_at = models.DateTimeField(verbose_name=u'Criado em',auto_now_add=True) filial = models.CharField(verbose_name=u'Unidade',max_length=256) My forms.py: class ContactDownloadAPIForm(forms.ModelForm): class Meta: model = ContactDownload My views.py: @throttle(zone='institucional-contact') @csrf_exempt @require_POST def contactdownload_contact_api(request): post = json.loads(request.body) form = ContactDownloadAPIForm(post.get('contactDownload')) if form.is_valid(): contact = form.save() response = {'contactDownload': {'id': contact.id}} return HttpResponse(content=json.dumps(response), status=200) else: errors = form.errors msg = '<br />'.join([errors.get(error)[0] for error in errors]) return HttpResponse(content=msg, status=400) Can anybody help me ? -
Check if an object exists in another models foreignkey field
I have a reviewing system for Subjects. User can review a subject, and users can like that review. class UserReview(models.Model): subject = models.ForeignKey(Subject, blank=True, null=True) user = models.ForeignKey(User) review = models.TextField(null=True, blank=True) likes = GenericRelation('Like') class Like(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: unique_together = (('content_type', 'object_id', 'user'),) How do I check if a user (eg UserA) exist in the likes of a user review? For now I am doing this way: if user_review_obj.likes.filter(user=UserA).count() > 0: // exist... But I am hoping there is another better way. -
How to config Django for Oracle RAC mode
We have two kinds of web servers. One is based on Java(tomcat + spring boot), while another is based on Python(Django). Recently we changed db from normal Oracle to RAC mode, which our Java server can successfully connect to it by following config: jdbc:oracle:thin:@(DESCRIPTION=(ENABLE=BROKEN)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=177.177.50.112) (PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=177.177.50.113)(PORT=1521))(LOAD_BALANCE=NO)(FAILOVER=YES))(CONNECT_DATA=(SERVICE_NAME=aldb)(SERVER=DEDICATED))) However for Django server, we can't find a proper way to config such connection. Anyone has experience to config Oracle RAC for Django? -
Which is a better real time app solution? Backend django directly connecting to the sensor or reading data from database?
I am developing a real time web app which will display data collected from sensor in browser. But it seems to be 2 ways to do it. On the frontend I am using Angular 4. And on the backend I am using django. First way is using Django to create a socket client and connect to the sensor dada collector (which is a raspberry pi) directly. On the raspberry pi there is a socket server listened on it. Once the django connects to raspberry pi, raspberry pi will push data to the socket. Then django can push data to frontend angular 4 using websocket (by django channels). Second way is running a standalone python socket client script connecting to the raspberry pi socket server and saving data into the database. Backend django will query the database every seconds and get the latest data. Then using websocket to push the data to frontend angular 4 in the same way as first way. Which is a better solution? -
Wagtail adding new pages
My current way of adding new pages to my wagtail site is the following: Edit the installed apps to include my new page INSTALLED_APPS = [ 'home', 'anotherpage', 'newpage', # this is new 'wagtail.wagtailforms', ... ] Copy the format of anotherpage to be my newpage cp -rf anotherpage newpage Edit my newpage/models.py references to anotherpage to be newpage. E.g. class Anotherpage(Page): becomes class Newpage(Page): And the newpage/migrations/0001_initial.py references Rename: mv feedback/templates/info feedback/templates/feedback and mv feedback/templates/feedback/info_page.html feedback/templates/feedback/feedback_page.html etc Then run python manage.py makemigrations Then python manage.py migrate Question This workflow feels quite inefficient, is there a better way to be doing any of the above? I'm new to python and wagtail. Any insight on what I could be doing better would be greatly appreciated -
Querying a Date range in django for the past 10 days
I'm trying to query a date range in django, but I'm not getting the expected results. I have a coupon model that has an end_date Field and I'd like to filter for all coupons that are expiring in the next 10 days. My model field looks like this: end_date = models.DateField() Here is what I have tried. Any help is appreciated: start = datetime.now() end = datetime.now() + timedelta(days=10) expiring_coupons = Coupon.models.filter(end_date__range=(start, end)) -
How to get Django ForeignKey to behave like a DateField
I have a Day class whose ID is a DateField. I have an Event class that links via ForeignKey to that DateField. I'd like to use ModelAdmin features like date_hierarchy but I get <class 'myapp.admin.EventAdmin'>: (admin.E128) The value of 'date_hierarchy' must be a DateField or DateTimeField. This is my models.py file: class Day(models.Model): date = models.DateField(primary_key=True) def __str__(self): return str(self.date) class Event(models.Model): date = models.ForeignKey(Day, to_field='date', related_name='events') bullet = models.TextField() def __str__(self): return self.bullet[:20] And admin.py has: class EventAdmin(admin.ModelAdmin): list_display = ('date', 'bullet') search_fields = ('bullet',) list_filter = ('date',) date_hierarchy = 'date' ordering = ('-date',) date_hierarchy doesn't work, and list_filter doesn't break things down by date. Is there a way to convert the Event ForeignKey field to a form that's seen as a DateField? I looked here and here unsuccessfully, although a feature coming in v1.11 may let me reference fields on related models directly. -
Why is Regex used in Django Routes?
What is the purpose of using Regex in the routes? -
Django Models (1054, “Unknown column in 'field list'”)
I am struggling with the following Unknown column in field list error. Any help would be really appreciated. OperationalError at /admin/login/person/ (1054, "Unknown column 'login_person.status_info' in 'field list'") Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/person/ Django Version: 1.11 Exception Type: OperationalError Exception Value: (1054, "Unknown column 'login_person.status_info' in 'field list'") Exception Location: D:\Users\Pubudu\AppData\Local\Programs\Python\Python36\lib\site-packages\MySQLdb\connections.py in query, line 292 Python Executable: D:\Users\Pubudu\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\Pubudu\\workspace\\village', 'D:\\Users\\Pubudu\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'D:\\Users\\Pubudu\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'D:\\Users\\Pubudu\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'D:\\Users\\Pubudu\\AppData\\Local\\Programs\\Python\\Python36', 'D:\\Users\\Pubudu\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages'] Server time: Fri, 19 May 2017 15:06:24 +0000 my models.py file : class Person(models.Model): person_id = models.UUIDField(primary_key = True, default=uuid.uuid4) #date_created = models.DateField(auto_now_add = True) first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 100) date_of_birth = models.DateField() email = models.EmailField() phone_number = PhoneNumberField() address_1 = models.CharField(max_length = 200) address_2 = models.CharField(blank=True, max_length = 200) city = models.CharField(max_length = 100) state = USStateField() zipcode = USZipCodeField() country = models.CharField(max_length = 40) status_info = models.TextField(blank = True) USER_TYPE = ( ('a', 'Patron'), ('b', 'Chef'), ('c', 'Driver'), ) user_type = models.CharField(max_length=6, choices=USER_TYPE, default='a', help_text='User type') USER_STATUS = ( ('a', 'Active'), ('b', 'License_approved'), ('c', 'Suspended'), ('d', 'Pending'), ('e', 'Terminated'), ('f', 'Terminated for ever'), ) person_status = models.CharField(max_length=1, choices=USER_STATUS, default='d', help_text='Registered user status') #class Meta: #ordering = ["-last_name"] def __str__(self): """ String for representing … -
Get Slug in DetailView
urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name="index"), url(r'^(?P<slug>[-\w]+)/$', views.DetailView.as_view(), name="detail"), ] views.py class DetailView(generic.DetailView): model = Company template_name = 'news/detail.html' def get_context_data(self, **kwargs): # Add in a QuerySet of all the books context = super(DetailView, self).get_context_data(**kwargs) response = requests.get('https://api.intrinio.com/news?identifier=SHOP', auth=requests.auth.HTTPBasicAuth( 'c447009707e06414dec4e58bcd042411', 'f4add05b8bdfe9c6bcff618de466ccb8')) context['articleList'] = response.json() return context Urls to visit: http://localhost:8000/news/SHOP/ So what my app has to do is, depending on the URL retrieve the slug and use the API of Intrinio to get a response. The response part all works, but currently its always the same company (?identifier=SHOP). I want to make it dynamic depending on the url. But im very new to Django and im not sure how I should pass the slug to the DetailView. I hope you can help. -
Changing Site Name in Django 1.9
I am currently following a tutorial which introduces a custom Bootstrap 3 template and builds a Django site using it. In the tutorial they suggest that one changes the following template snippet: <a class="navbar-brand" href="index.html">Start Bootstrap</a> to the following snippet. <a class="navbar-brand" href="/">{{ request.site.name }}</a> However, when I make this change, no site name shows. I am wondering where I should be setting this name. If it helps, I am using Django CMS and there is only one site called example.compopulated in the Sites section of the Administration. -
nginx 502 error not showing debug info
I'm working on a django/nginx site and am currently trying to get the configuration set up properly. The problem is proper debugging (I'm more used to Apache): When i introduce a code error in python (e.g. delete half the file so it's complete rubbish), I don't always get a nice debug info page but sometimes it's just a non descriptive 502 page (e.g. importing file missing or similar). I've set the error log path and debug level in the nginx.conf, however nothing is getting logged except the restarting event of ngnix. So how would one debug an error like this? Shouldn't it tell me somewhere "import file doesn't exist" or anything similarly useful? Thanks! -
Register and Login at the same time in Django using django-registration
I've been beating around the bushes for some time regarding this and I couldn't find any straight-forward way to do it, so I thought it's time to ask here for some guidance/help. What I'd like to accomplish: when a user logs in for the first time (using an email and a password), his data will be used the next time he's trying to log in. Basically, the registration form is also the login form. The flow would be the following: if the email doesn't exist in DB -> create a User which contains the inserted data (this info will be used at the next login). Then redirect the user to the home page. if the email exists, warn the user and ask for another one (stay on this page). Now, for this to work, I've been told to use the simple workflow mentioned on django-registration page. Being a newbie with Django, I've really tried to come to a solution, but I don't find that tutorial as explicit as it should for such an important task. My project (named odt), which contains a single app (named odt_app) has the following structure: The main urls.py: from django.conf.urls import include, url from django.contrib … -
Set UTC when fixing naive datetimes with django.utils.timezone?
I'm using Django 1.9. I have a model with a DateTimeField: class myModel(models.Model): created = models.DateTimeField(blank=True, null=True) And I have some naive text datetimes that look like this: str = "2017-05-18T16:38:23" If I do this: d = datetime.strptime(result['last_modified'], "%Y-%m-%dT%H:%M:%S") mymodel.last_modified = dt_aware I get a warning: RuntimeWarning 439 /usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1430: RuntimeWarning: DateTimeField CV.last_modified received a naive datetime (2015-04-07 09:09:20) while time zone support is active. So I'm trying this instead, but I'm aware that instead of current timezone I should really be using UTC, because I know the datestrings are UTC: d = datetime.strptime(str, "%Y-%m-%dT%H:%M:%S") dt_aware = tz.make_aware(d, tz.get_current_timezone()) mymodel.last_modified = dt_aware How can I amend this to use UTC rather than current timezone? I don't want to disable timezone support in my app. -
In Django, how do I serialize a QuerySet that returns a dict object (created with .values())
In Django 1.10 I am trying to serialize an QuerySet that I obtained from the following query: events_in_period = Event.objects \ .filter(timestamp__gte=start_day, timestamp__lte=end_day, request__isnull=False, name=EventType.COMPLETED) \ .annotate(date=TruncDay('timestamp')) \ .values('date') \ .annotate(completed_count=Count('id')) \ .order_by('date') The main thing is the .values() statement that makes this statement return a QuerySet that contains a dict rather than a Django model instance. Therefore the following calls to serialize it from django.core import serializers output = serializers.serialize('json', result) fail with the following error: AttributeError: 'dict' object has no attribute '_meta' Any suggestions on serialization without omitting the .values() as I need them for brevity. -
django: multiple db in admin [how-to]
Could you please advise in the following: registry is the project, BGP is the app, default is the sqlite db, registry is a postgres db the admin.py looks like this: class MultiDBModelAdmin(admin.ModelAdmin): # A handy constant for the name of the alternate database. using = "registry" def save_model(self, request, obj, form, change): # Tell Django to save objects to the 'other' database. obj.save(using=self.using) def delete_model(self, request, obj): # Tell Django to delete objects from the 'other' database obj.delete(using=self.using) def get_queryset(self, request): # Tell Django to look for objects on the 'other' database. return super(MultiDBModelAdmin, self).get_queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request, **kwargs): # Tell Django to populate ForeignKey widgets using a query # on the 'other' database. return super(MultiDBModelAdmin, self).formfield_for_foreignkey(db_field, request, using=self.using, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): # Tell Django to populate ManyToMany widgets using a query # on the 'other' database. return super(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request, using=self.using, **kwargs) class BGPcommunitiesAdmin(MultiDBModelAdmin): list_display = ("comm_name", "comm_value", "used_as", "label", "modified_on") search_fields = ("comm_name", "comm_value", "label") list_filter = ("used_as", "modified_on") admin.site.register(BGPcommunities, BGPcommunitiesAdmin) registryadmin = admin.AdminSite("registryadmin") registryadmin.register(BGPcommunities, BGPcommunitiesAdmin) and the urls.py looks like this: from BGP.admin import registryadmin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^registryadmin/', registryadmin.urls), ] The issue is that I cannot save any record in … -
What are important tricks about saving heavy media files in production?
What should I know about saving files in production? I need to save lots media which are pdf files. The only thing I know so far, is that I shall rename pdf files into my own naming system (for example by overwriting storage in django). But what else is important ? Or that's all, just saving all files like 1.pdf,2.pdf,3.pdf,4.pdf.. in one media folder and it will work in long term without any other tricks and optimization? I am using django1.8 and python 2.7, but I guess it's very general question regarding running production server at all . I hope it's not off topic, as far I faced the lack of information on the issue. -
Passing status of object as success or error
My first attempt with Ajax responses. I'm Trying to turn my non-ajax login view into an ajax view. The view goes through as it should, i'm logged in or not logged depending on my pass. The problem is with success function - it is not performing it's action after the jsonresponse. What i get is the directory like {'status': 'ok'} instead of redirection to login or frontsite. view: class LoginAjaxView(FormView): form_class = LoginForm template_name = 'registration/login.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request, user) if cd['rem']: self.request.session.set_expiry(0) messages.success(request, 'Successfully logged in.') data = { 'status':'ok' } else: messages.error(request, 'This account is banned.') data = {'status': 'ban'} else: messages.error(request, 'Invalid combination of username and password') data = {'status': 'badlog'} else: messages.error(request, 'Unable to log in.') data = {'status': 'invalidform'} return JsonResponse(data) Script with ajax: $(document).ready(function () { $('#id_form').on('submit', '#id_form', function (e) { e.preventDefault(); $.ajax({ type:'POST', url: {% url "ajax_login" %}, data:{ id_username:$('#id_username').val(), id_password:$('#id_password').val(), rem:$('#id_rem').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, error: function (xhr, ajaxOptions, thrownError) { alert(thrownError); }, success:function(result){ if(data['status']=='ok'){ window.location='{% url "frontsite" %}'; } else { window.location='{% url "ajax_login" %}'; } } }); }); }); -
GraphiQL works locally but in production the output shows content from base.html (Django project)
I successfully installed graphene and graphene-django into my project and am able to make queries with the GraphiQL interface in my local environment. When I deployed my app to production and visited the GraphQL endpoint, the GraphiQL interface is not working and is showing the contents of my base.html in the output section. The "Docs" will not load anything either. There must be something in the production configuration that is interfering with GraphQL but I haven't been able to pin it down yet. Any ideas would be appreciated!