Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to keep content in the left sidebar data in django page
I am building a website based on django.Below find my models: model.py class Projectname(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Jenkinsjobsname(models.Model): projectname=models.ForeignKey(Projectname) jobsname = models.CharField(max_length=200) def __str__(self): return self.jobsname view.py def index(request): project_name=Projectname.objects.order_by('-name')[:5] context = {'categories': project_name} return render(request,'buildstatus/index.html', context) def detail(request,projectname_id): jobs=Projectname.objects.get(pk=projectname_id) context = {'jobs': jobs} return render(request,'buildstatus/detail.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<projectname_id>[0-9]+)/$', views.detail, name='detail'), ] detail.html {% extends "base.html" %} {% block text %} <ul class = "nav nav-tabs" > {% for jenkinsjobsname in jobs.jenkinsjobsname_set.all %} <li><a href= "#">{{jenkinsjobsname.jobsname}}</a></li> {% endfor %} </ul> {% endblock %} index.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% endblock %} base.html <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <div class="nav-collapse collapse"> <ul class="nav pull-right"> <li><a href="/admin/">Login</a></li> </ul> <ul class="nav navbar-nav"> <li class="active"><a href="/buildstatus/">Home</a></li> </ul> </div> </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="span3"> <div class="well sidebar-nav"> <h3>PROJECTS</h3> {% block text1 %} {% endblock %} </div> </div> <div class="span3"> {% block text %} {% endblock %} </div> … -
i can not import py module when i using python django
that'my first time to ask question here. i'm learning django now, I start a project in virtualenv. that's my file file picture when I trying from polls import views module under urls.py. module picture it shows : No module named 'polls' I search for the python documents and tring to modify it like: from . import views or from .polls import views but it shows:Parent module '' not loaded, cannot perform relative import some people say it's sys.path problem.So I added a current sys.path in the virtualenv. But it can not work either. How to solve the problem ? .... -
Order Django Query by DateTime Field Day - 1.9
I have a model in my Django application that has a DateTime field, and want to order those models simply by day, and than by that models first name. I have a meta class on my model that sets the ordering by its date time field in descending order, but it is picking up the time as well. This SO question showed promise, but the two accepted answers are for any Django version 1.8 or lower, and 1.10 or higher, and I am using Django 1.9 hah. I looked through the Django documentation to try and find a way to do this, but am have a lot of difficulty. Maybe I am just getting tunnel vision. Does anyone know of an equivalency to Django.db.models.functions.Trunc so I can use the accepted answer from the Stack Overflow answer mentioned, or do they know of a way to only order on a date time fields day ? Model import datetime import logging from django.db import models, IntegrityError from django.db.models import DateTimeField #from django.db.models.functions import Trunc <- only available in 1.10 from account.models import Account from dealer.models import Dealer class DealerLead(models.Model): user = models.ForeignKey(Account) dealer = models.ForeignKey(Dealer) assigned = models.BooleanField(default=False) assigned_to = models.ForeignKey(Account, related_name='leads', … -
Django, TinyMCE field serialization inconsistencies
In Django I have a form. There is one form field that has TinyMCE editor attached to it. I want to check if form has changed so if it has, pop up modal should show. I achieve this by this code which runs on every page load: $($('my-form').each(function() { $(this).data('init') = $(this).serialize(); }) $(window).bind('beforeunload', custom_validator); ); And of course the custom_validator function is in the same file: function custom_validator() { $('my-form').each(function() { if ($(this).data('init') != $(this).serialize()) { return "Form has unsaved changes."; } }) } When page loads, the data('init') is serialized with the TinyMCE field as well. If the TinyMCE field contains multiple lines, serialize() represents them with '%0D%0A'. Which is fine. If I want to navigate away from the page or just reload it after changing the form, the 'beforeunload' event triggers the custom_validator function and prevents me to do that which is good as well. Now, the problem begins when I load the page and I don't make any changes to the form and just want to navigate away from page, the popup window occurs and warns me that there are changes on form, even I didn't change anything. It turns out that if I have multiple … -
Wagtail;: ValueError: too many values to unpack (expected 2) when creating a large custom StructBlock for StreamField
I'm creating a StructBlock for StreamField. The goal is to create a block that will upload an image as well as a lot of metadata. The metadata is a mixture of CharBlocks, ImageChooserBlocks and RichTextBlocks. When I want to make the changes in database using makemigrations I receive the error "ValueError: too many values to unpack (expected 2)" Preceeding that I get: File "C:...\models.py", line 66, in CatalogueIndexPage 'image', TurnerImageBlock(), File "C:...\wagtail\lib\site-packages\wagtail\wagtailcore\fields.py", line 51, in __init__ self.stream_block = StreamBlock(block_types, required=not self.blank) File "C:...\wagtail\lib\site-packages\wagtail\wagtailcore\blocks\stream_block.py", line 47, in __init__ for name, block in local_blocks: I was thinking that it may be due to too many fields. But that shouldn't be a problem. I have also looked at formatting but can't see any. I've included the models.py code below. from datetime import date from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailcore import blocks from wagtail.wagtailadmin.edit_handlers import StreamFieldPanel from wagtail.wagtailimages.blocks import ImageChooserBlock class TurnerImageBlock(blocks.StructBlock): image_title = blocks.CharBlock(required=True) thumbnail = ImageChooserBlock() full_image = ImageChooserBlock() copyright_conditions_of_use = blocks.CharBlock() unique_identifying_number = blocks.CharBlock() date_of_submission = blocks.DateTimeBlock(default=date.today) # person submitting person_submitting_images = blocks.CharBlock() current_owning_inst_person = blocks.CharBlock() inst_personal_unique_impression_accession_no = blocks.CharBlock() inst_personal_unique_image_accession_no = blocks.CharBlock() # Dimensions impression_physical_dimensions = blocks.CharBlock() size_of_paper = blocks.CharBlock() size_of_plate_impression = blocks.CharBlock() size_of_picture = blocks.CharBlock() # … -
Access to specific user S3 bucket using IAM roles and federated users
our project aims to create a platform powered by Django in Python which allow users to create instance and retrieve access to their S3 bucket. The s3 buckets would be stored in our bucket with S3://User1 , S3://User2 etc... We understood that we need to use IAM roles when creating the instance, these roles would have variables with the username. The question is how can we give to the IAM roles that username as a parameter? Do we need to have a federated login using Cognito or other? If yes which Identity Provider would you advise us to use? (We work with Python and Django). Thank you ! -
django - How to get location through browser IP
I have a really basic django app to get weather. I need to get user's location to show them their current location's weather. I am using GeoIP for that. But an issue has come up that GeoIP does not have information of all the IP addresses. It returns NoneType for those IP addresses. I want to know if there is any other precise way by which I can info about User's current latitude and longitude, like maybe browser API? It should not miss any User's location like GeoIP does. -
Creating user views using django admin functionality
i'm wondering what is the right way of extending django admin functionality. I mean i've some table in admin site and it has a pretty looking style table as well as sortable columns by clicking on the table header and all i want is to extend that table appearance in user view but making it read only. It would be nice if i could have authentication functional available. -
annotate second minimal value in django ORM
I have two classes: Subject and Visit (where visit has a subject field) When performing retrieving of Subject data I can add field (annotate objects) with additional min/max data from related tables like: Subjects.objects.annotate(min_date=Min('visit_set__datetime_begin')) I would like to do similar thing but with second to the lowest value. Is it possible without iterating over all elements or executing custom SQL? -
Connection refused on socket.connect (Django app deployed on uWSGI + Nginx)
I have a Django application deployed on a VM using uWSGI & Nginx setup. I would like to print some data, by passing the required information to a printer that is configured on the same network using a socket: printer_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) printer_socket.connect(('10.125.125.2', '9001'])) printer_socket.send(bytes(source='data', encoding='utf-8')) Note: the IP address and the port are here for illustration purposes. Problem: I get a Err 111 Connection refused error, however. The error is triggered at the printer_socket.connect step. Additional information: The python code that initializes the socket, connects to the required IP address/Port and sends the data works fine when it's run from the python interactive shell. Question: What do I need to configure in order to allow opening sockets from a django web application, deployed using uWSGI and Nginx? Please keep in mind that the configuration of the project is out of the scope of this question. I don't have troubles configuring the app. The app works fine. I am specifically interested in how to allow opening sockets from a web app, served using uWSGI + Nginx setup Thank you. -
django polimorphic StackedPolymorphicInline.Child and modeltranslation: how to set?
From the documentation example: class PaymentInline(StackedPolymorphicInline): """ An inline for a polymorphic model. The actual form appearance of each row is determined by the child inline that corresponds with the actual model type. """ class CreditCardPaymentInline(StackedPolymorphicInline.Child): model = CreditCardPayment class BankPaymentInline(StackedPolymorphicInline.Child): model = BankPayment class SepaPaymentInline(StackedPolymorphicInline.Child): model = SepaPayment model = Payment child_inlines = ( CreditCardPaymentInline, BankPaymentInline, SepaPaymentInline, ) How can I set inlines childs to be used with modeltranslation? -
Reuse Abandoned Django User IDs?
I have a new public-facing Django/PostgreSQL-based web site that requires users to create a new username/password and then fill out a profile that requires three more screens (forms) after the initial username/password page to complete their membership. As you would expect, I have a small number of users that don't complete the entire signup process leaving me with abandoned user IDs. Do either Django and/or PostgreSQL provide any convenient means of recovering and reusing these abandoned user IDs? -
How to deal with certain tags or characters in API to deal with XSS?
In django,i have a following serializer class test(serializers.Serializer): first_name = serializers.CharField(max_length=100, required=True) last_name = serializers.CharField(max_length=100, required=True) address = serializers.CharField(max_length=100, required=True) I want to stop the untrusted user from using(script tags OR alert(1233)) kind of things in some charfields since the rest API having above as a request serializer is going to be open. -
Django Localhost not loading static files
I have a working app and have downloaded the relevant django files locally (via git) and am trying to run the app locally. However, static files are not loading. I receive the following console error when accessing, say, the home page (http://localhost:8000/home/) of the app: GET http://localhost:8000/static/imported_JS/jquery/jquery.min.js net::ERR_ABORTED or this error: http://localhost:8000/static/globe.png 404 (NOT FOUND) In my settings.py file, I can confirm: BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)),'..')) # i.e. location of settings.py file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn/') I can also confirm there is indeed a static_cdn/ file directory and it does contain the relevant static files. The live dev and prod versions of the app work (which are hosted on separate web servers) but, for whatever reason, when running the app locally, static files are not served. Any ideas on how to have the localhost server static files? Most of the answers on SO regarding this type of question relate to mistakes with setting up STATIC_URL vs. STATIC_ROOT but these appear to be correct (at least on dev and prod). Let me know if you require more info. Thank you. -
Django allauth facebook authentication Incorrect Value
I have earlier created a Facebook app version 2.4 in my Facebook account and got the access token to get validated using Django allauth, this works fine, but if i create a new app in Facebook with version of 2.10 and try to validate the access token it shows "Incorrect Value". whether i need to update the plugin or any fix is available kindly help me. -
How to sort queryset output in view django?
I have these two models : class Home(db_interface.Entity): patient = models.ForeignKey(Patient, help_text='Patient') sode = models.ForeignKey(Sode, help_text='sode') class Sode(db_interface.Entity): start_date = models.DateField(validators=[validate_date_range], null=True, help_text="Start Date") path = models.ForeignKey('Path', null=True, blank=True) help_text="Path") and my view is inherited from a ListView of Django .To return a queryset I override get_queryset() method : def get_queryset(self): instance = self.get_instance() if instance: return Sode.objects.filter(patient=instance).select_related('path').prefetch_related( 'home_set') return [] to list data in my template I use a for loop : {% for h in sode.home_set.all %} data is displayed in lists perfectly, but what I want to do now is to filter the list (not the standard filter approach) I mean the items in the list will be modified depending of the status of some items . I tried to write a custom filter so that the every time my template is loaded I have data in the list are shown as I want. But I recognized that in my filter I used objects from database which must be in the view to separate presentation code from data logic, so filtering models musn't be in a filter I ended up by moving the logic I wrote in the custom filter to a function in my model's ListView … -
How to implement the SimpleMiddleware?
I am struggling getting MiddleWare to work. I put this in my settings.py: MIDDLEWARE_CLASSES = [ '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', 'portal.middleware.SimpleMiddleware' ] and I implemented this class in portal/middleware/MiddleWare.py: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response But when running, I get a TypeError: TypeError: __init__() takes exactly 2 arguments (1 given) -
log a message in my terminal server (localhost:8000)
def clean_expired_requests(): now = datetime.datetime.now() qs = Request.objects.filter( expires_at__date=now, state__in=[ 'documents', 'validation', 'evaluation', 'signature']) for req in qs: log.debug('Request %s expired' % req) req.expired_at_state = req.state.name req.save() req.expire() EmailFromTemplate('expired-request').send_to(req.customer.user) I am working on a Django project with this method. I would like to insert something which will advise me that has been called. I thought it could write me a message in my terminal server 'clean_expired_request has been called!'. How could I do such thing? -
Simple Django Form
I'm trying to implement a Twitter-like follow system (one user can follow and be followed by many other users). I've tried a number of ways, but I keep getting errors. Currently, every time I drop debuggers or print statements throughout the form, I find that I don't ever get into the clean methods, nor is kwargs ever populated with values. I want to be able to pass in the follower & following as arguments to the Form and just assign them in the __init__ but everything is going wrong. When I get the response back in Javascript (React & Redux), all I'm getting is errors for both follower & following saying "This field is required." Here's what I've got so far: Models class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Meta: verbose_name = 'user' verbose_name_plural = 'users' class UserFollow(models.Model): follower = models.ForeignKey('User', models.CASCADE, related_name='follows') following = models.ForeignKey('User', models.CASCADE, related_name='followed_by') class Meta: unique_together = ('follower', 'following') def to_user(self): return { 'id': self.pk, 'follower': self.follower.pk, 'following': self.following.pk } Views def follow(request, id): following = User.objects.get(pk=id) form = UserFollowForm(follower=request.user, … -
How can I delete form field data in django after submit
I'm working on a django project where during registration, a user can submit a code to get special discounts. The validation of the discount codes is already working nicely, but I'm missing one beautifying aspect: After the user submits an invalid code I want to empty out the input field; i.e.: def validate_code(value): # check code for validity or raise ValidationError class CodeForm(forms.Form): code = forms.CharField(validators=[validate_code]) # in my views.py def code_verification_view(request): if request.method == 'POST': form = CodeForm(request.POST) if form.is_valid(): # proceed with given code else: # modify form to return an empty html input for the code field # this is where I'm stuck form.fields['code'].value = '' # ... render the form in a template The end result should be a form with an empty input field, but the validation errors showing. The behavior should be similar to how password input fields are emptied if the form verification fails. -
Django 1.11 error with change from views based in fuction to views based in class
I have a problem when I want change from views based in function to views based in class. I change the def index by class IndexView in my views.py and in my url.py I change url(r'^$',views.index, name="index"), by url(r'^$',IndexView.as_view(), name="index"), but all see correct, but I have a mistake because don't find IndexView My urls.py is the next: from django.conf.urls import url, include from . import views urlpatterns = [ #url(r'^$',views.index, name="index"), url(r'^$',IndexView.as_view(), name="index"), url(r'^panel/$',views.main_panel, name="panel"), url(r'^panel/evento/nuevo/$',views.crear_evento, name="nuevo"), url(r'^panel/evento/(?P<evento_id>\d+)/$',views.detalle_evento, name="detalle"), url(r'^panel/evento/editar/(?P<evento_id>\d+)/$',views.editar_evento, name=""), ] My views.py is the next: from django.shortcuts import render, redirect, get_object_or_404 from .models import Event, Category from django.views.generic.base import TemplateView from myapps.users.models import User from .forms import EventoForm from django.core.urlresolvers import reverse # Create your views here. def login(request): return render(request, "login.html", {}) #def index(request): # events = Event.objects.all().order_by('-created')[:6] # categories = Category.objects.all() # return render(request, 'events/index.html', {'events': events, 'categories': categories}) class IndexView(TemplateView): template_name = 'events/index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['events'] = Event.objects.all().order_by('-created')[:6] context['categories'] = Category.objects.all() return context def main_panel(request): #organizer = request.user.username events = Event.objects.filter(organizer__username='').order_by('is_free', '-created') cantidad_eventos = events.count() return render(request, 'events/panel/panel.html', {'events': events, 'cantidad': cantidad_eventos}) def crear_evento(request): if request.method == 'POST': modelform = EventoForm(request.POST, request.FILES) if modelform.is_valid(): organizador = User.objects.get(pk=3) nuevo_evento = … -
Django REST ImageField default is absolute url?
Softwares: Python3.6.2 Django1.11 djangorestframework-jwt==1.11.0 djangorestframework==3.6.4 I can not get url from the Django REST when I am using it with jwt_response_payload_handler https://gist.github.com/elcolie/1e291af47aa7312ec7d06f76c91f797e Attempt: That keyword argument use_url=True does work with viewset, but it does not when I integrated to the customized jwt function. References: Django serialize imagefield to get full url -
How can i store the form values in csv using django instead of usind Database?
Name,Email (entered details from form values) Fields store in csv file using python django -
HTML File link - force download always
I have a Django view that renders a list of uploaded files, and the user can click on them to begin the download. When the project was deployed, we found there's one file that browsers open instead of download it. It seems related to the .dxf extension. This is how the link is created: <a href="{{ MEDIA_URL }}{{ file.url }}" target="blank">...</a> As a result: http://localhost:8003/media/folder/whatever.dxf So, why the same browser behaves differently? if I run it on localhost, then it downloads the file. But accessing the real server, it'd open it. Can I prevent the server to open them in browsers? -
Getting two letter language code from get_current_language
I am using Django internationalization and use the get_current_language call to get the current language. However, that is a language code plus region code (e.g. en-gb), while I only want the language code (e.g. en). How can I get just the two-letter language code?