Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django storages and setting ACL per object
I am using django-storages and google-cloud-storage backend. what I currently have is the following. from django.conf import settings from storages.backends.gcloud import GoogleCloudStorage from storages.utils import clean_name from django.conf import settings class PublicImageUploadStorage(GoogleCloudStorage): bucket_name = settings.IMAGES_BUCKET_NAME or None file_overwrite = settings.IMAGES_OVERWRITE or True def make_public(self, name): name = self._normalize_name(clean_name(name)) blob = self._get_blob(self._encode_name(name)) return blob.make_public() this is slow because it looks up blob object by name then return it so I can make it public. what is the most efficient way of setting object ACL to be public-read before saving the object to google storage ? -
Trying to create a Django model instance via a form, but I only want to extract some fields from the form and set others manually
I'm trying to create a gallery app in Django. I have two models: Pic and Profile, which represent an individual picture and a user profile respectively. Each user has a profile instance created when they sign up for the website. Here are the models: class Profile(models.Model): user = models.OneToOneField(User, related_name="profile") class Pic(models.Model): profile = models.ForeignKey(Profile, blank=True, null=True) photo = models.ImageField(upload_to = "photos/%Y/%m/%d/") I want users to be able to upload an image through an HTML form. When they upload the image I want to create a Pic whose ImageField corresponds to the upload. I've created a ModelForm for the Pic model to accomplish this. Here's the form as of now: class PicForm(forms.ModelForm): class Meta: model = Pic fields = ('photo',) And the upload_image view: def upload_image(request): if request.method == "POST": form = PicForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: return redirect('upload_image') else: form = PicForm() return render(request, 'pics/upload_image.html', { 'form': form }) So the problem is, I want the user to be able to set the photo field of the new Pic via the form, but not the profile field. I want that to be set to the user's profile. How can I accomplish this? -
How to compile a .java file which is been arbitrarily named different from public class name
I had been creating an online judge platform like codeforces.com on Django recently. Now, I'm struck across a problem that the user may possibly upload a Java file for testing with the filename different from the public class defined inside it. Yet, I should compile it automatically. So, what could be a possible solution to this? -
django check if user is allowed to add Post
i am creating a blog just for practice and i want to allow some users to add/delete a post how to add this BooleanField to users and check if allowed in templates -
How can I load data from tables before project refactoring and add them to new tables?
I was refactoring my project and after that I have situation in my database shown below. I changed name of my project from backend2 to backend. Normally I could delete all backend2 tables however I have there data that I need. Backend tables are empty. My goal is to have data from tables from backend2 in my backend tables. Then I don't need backend2 tables and I can delete them. Any ideas how can I do this? public | backend_table1 public | backend_table2 public | backend_table3 public | backend_table4 public | backend_table5 public | backend2_table1 public | backend2_table2 public | backend2_table3 public | backend2_table4 public | backend2_table5 -
How to check dates basing on year and week number in Python
I'd like to check the days for a given week_number. for an instance, if I input year 2017 and weekNumber 43, I would like to receive all dates for that week, in this case 22-28.10.2017. Is it possible to do in Python ? was trying to find something using google, but unsuccessfully Thanks in advance, -
Use cookiecutter-django with Celery 4.x
I use cookiecutter-django with celery==3.1.25. Now I need use tasks scheduler, and my opinion, best way for this - it's celery beat. But here I found information that celery-beat works with Celery version 4.x Here I saw the information that pyup-bot on July 24 offered to update Celery to version 4.1.0, but this issue is still open. Prompt, how to be in my situation? I like cookiecutter-django and I'm using it now in my project, but also, I really need a task scheduler. I have not yet tried to replace the version of Celery, but I think that this will lead to a number of mistakes, otherwise it would have been done before me. -
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?