Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / AWS S3 - The bucket you are attempting to access must be addressed using the specified endpoint
I have a Djagno project which is producing PDF and Excel download files. For the most part these are working fine but when the PDF file gets above about 9.7k records I start getting the following error (the same occurs for the Excel file but at a high record count). <Error> <Code>PermanentRedirect</Code> <Message> The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint. </Message> <Bucket>myBucket</Bucket> <Endpoint>myBucket.s3.amazonaws.com</Endpoint> <RequestId>1234567890ABCDEF</RequestId> <HostId> AVERYLONGHOSTIDCODE= </HostId> </Error> It seems I have an issue with the filesize (even though it isn't being saved - the PDF is presented straight onto the screen and the Excel goes straight to download) but that could be a symptom of something else. This is a python 2.7, Django 1.4 project. I do not think this is an s3 issue because, according to this answer, you can "Write, read, and delete objects containing from 1 byte to 5 terabytes of data each. The number of objects you can store is unlimited." Therefore, I suspect it is a Django or Python issue. Does anyone have any experience with a similar issue or thoughts? Any help most welcome. -
`SyntaxError: no binding for nonlocal 'topics_with_log_tag' found` although it's bounded
I'd like to fetch topics with a specified 'log' tag: Within the nested function get_topics_with_log_tag, I set variable topics_with_log_tag nonlocal: def log(request): """Show all topics and entries with log tags""" topics = Topic.objects.all() #select entries with log tag def get_topics_with_log_tag(topics): nonlocal topics_with_log_tag topics_with_log_tag = [] for topic in topics: for entry in topic.entry_set.all(): if "#log" in entry.tags: topics_with_log_tag.append(topic) get_topics_with_log_tag(topics) It throw SyntaxError: SyntaxError: no binding for nonlocal 'topics_with_log_tag' found Actually, I did bind it topics_with_log_tag = [] The above code could be rewrite in a redundant way as topics = Topic.objects.all() #select entries with log tag def get_topics_with_log_tag(topics): # nonlocal topics_with_log_tag topics_with_log_tag = [] for topic in topics: for entry in topic.entry_set.all(): if "#log" in entry.tags: topics_with_log_tag.append(topic) return topics_with_log_tag topics_with_log_tag = get_topics_with_log_tag(topics) What's the problem with my usage of nonlocal? -
Push Notification not working with push notification time
When I am using push notification in python then I am not able to sent push notification time as per required Example : 1m or 60m etc I am using https://github.com/olucurious/PyFCM this in application. Please give me example how to send push notification time as per required registration_id = request.POST['registration_id'] message_title = request.POST['message_title'] message_body = request.POST['message_body'] result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) Where we need to sent push notification type for this application When I am setting time then getting so many problems and example not exit in whole example. -
django testing class based view
I have a Class based view defined as: class Myview(LoginRequiredMixin, View): def post(): #....... to test this view i tried this class MyViewTest(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='jacob', email='soos@i.com', password='vvggtt') def view_test(self): # Create an instance of a POST request. request = self.factory.post('/my-url/') request.user = self.user response = MyView(request) print (response,"**") self.assertEqual(response.status_code, 200) But this gives this error. response = MyView(request) TypeError: __init__() takes 1 positional argument but 2 were given I understand why this error is coming (cinstructor of MyView has 2 ars) but how do i remove it? i couldnt get the details on searching. -
Foreign key to get column from another model - Django
I have been trying to add a new column to my TrainingSubject model called "email" and link its value to another model (Training) via foreign key, and then display it all on front end (back is django, front is react. I've added this line to TrainingSubject model: email = models.CharField(_('Email assigned'), max_length=100, default='', blank=True) and this one to Training model: email_to = models.ForeignKey(TrainingSubject, related_name='manager_email', default='', blank=True) so it all reads as follows: class TrainingSubject(models.Model): """TrainingSubject model for storing subjects.""" name = models.CharField(_('name'), max_length=160, unique=True) email = models.CharField(_('Email assigned'), max_length=100, default='', blank=True) def __str__(self): return self.name class Meta: verbose_name = _('Training subject') verbose_name_plural = _('Training subjects') class Training(models.Model): """Training model for storing trainings.""" subject = models.ForeignKey(TrainingSubject, verbose_name=_('subject'), related_name='trainings') email_to = models.ForeignKey(TrainingSubject, related_name='manager_email', default='', blank=True) date = models.DateTimeField(_('date')) timezone = models.CharField( The migration cannot be applied, I get this error every single time I start creating these things. Running migrations: Rendering model states... DONE Applying sonel_core.0089_training_email_to...Traceback (most recent call last): File "/home/vagrant/.pyenv/versions/cms/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "email_to_id" contains null values Previously I tried to add it all in one step only, now I have broken it down to two steps: 1. add email to TrainingSubject (which work … -
Elastic Beanstalk (+Django + Postgres): How to find RDS_VARIABLE?
I'm trying to configure my Django Server on AWS Elastic Beanstalk. I just followed these instructions to set up a database and it has finished. For some reason though, I can't acces the environment variables: RDS_DB_NAME RDS_USERNAME RDS_PASSWORD RDS_HOSTNAME RDS_PORT When I type in eb printenv, I just get the variables that I manually set using eb setenv. How can I get access to the environment variables from the postgresql database? -
Change Django Users List Display
I am trying to change the Users view in Django Admin to show different fields (now it shows by default: username, email address, first name, last name, staff status) I have tried this in the admin.py file: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User # Register your models here. UserAdmin.list_display = ['email', 'first_name', 'last_name', 'is_active', 'last_login'] admin.site.unregister(User) admin.site.register(User, UserAdmin) However I cannot get my admin Users view to change. Is there anything else I need to do? I am using Django 2.0 -
Update statement in Django ORM
How to implement sql statement update table1 set field1 = field2 using Django ORM. -
JQuery POST request being sent as GET in Django
So I've had a look at a bunch of questions and I still can't figure out why AJAX is sending my POST request as a GET in my Django application: JS: get_profitability_limits: function() { // Gets Profitability limits from backend. var that = this; $.ajax({ url: '/settings/settings_management_simulator_profitability_limits', method: 'GET', success: function (data) { that.profitability_limits = data.profitability_limits; if (! that.profitability_limits.structure && that.profitability_limits.company_areas && that.profitability_limits.consumer_type_keys) { that.profitability_limits.structure = that.default_profitability_limits(); } // Show cell. $('#simulator_profitability_limits_loader')[0].className = ""; $('#simulator_profitability_limits_main')[0].style.display = 'flex' } }); }, save_profitability_limits: function() { // Saves profitability limits to database. var that = this; $.ajax({ url: '/settings/settings_management_simulator_profitability_limits', method: 'POST', data: { 'structure': that.profitability_limits.structure }, success: function (data) { } }); }, View: @login_required @permission_required('smdb.can_manage_simulator_settings') def manage_settings_profitability_limits(request): """ View for handling profitability limits in Simulator. """ if request.method == 'GET': company_areas = list(_get_selected_energy_company(request).country.area_set.all().order_by('key').values_list('key', flat=True)) consumer_type_keys = CONSUMER_TYPE.MAP.keys() # TODO: Change when consumer types are added back in. consumer_type_keys = [2] structure = EnergyCompanyPreferences.get_setting('profit_simulator_profitability_limits') return JsonResponse({ 'profitability_limits': { 'company_areas': company_areas, 'consumer_type_keys': consumer_type_keys, 'structure': structure } }) elif request.method == 'POST': profitability_limits = json.loads(request.POST.get('structure', '{}')) if profitability_limits: EnergyCompanyPreferences.update_setting('profit_simulator_profitability_limits', profitability_limits) return JsonResponse({'saved': True}) Every time I fire save_profitability_limits() a GET request is sent with the following header: GET /en/settings/settings_management_simulator_profitability_limits HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Accept: … -
Create breadcrumb when I have a self ForeignKey table connected to M2M table
The problem I want to solve is in Django, but is is strongly related to how I query in the database. I have a model/table Category that has a ForeignKey to itself: | id | name | parent_id | 1 | name1 | Null | 2 | name2 | Null | 3 | name3 | 1 | 4 | name4 | 1 | 5 | name5 | 3 | 6 | name6 | 3 | 7 | name7 | 5 A Parent Category can have multiple Subcategories and there is no depth limit; Also I have a model/table Product that has a ManytoMany Relation with Category. A Product can be in multiple Categories and a Category can have multiple Products Intermediary Table | id | product_id | category_id | 1 | 1 | 1 | 2 | 1 | 2 | 3 | 2 | 1 | 4 | 2 | 3 | 5 | 3 | 5 | 6 | 3 | 4 | 7 | 3 | 7 Product Table | id | name | 1 | name1 | 2 | name2 | 3 | name3 What I need: 1) for a breadcrumb to get the first set … -
Django Related Models - magic behind the scenes
I was trying to find the answer in Django Documentation, but failed to do so. Can anyone please explain how does Django "match" the objects of the related models? eg. I have two models, and I am showing Django that they are related: class Reporter(models.Model): # ... pass class Article(models.Model): reporter = models.ForeignKey(Reporter, related_name='report') Then the magic happens and Django matches the two models, and adds _id field. My question is: How does Django know which objects of those two models are related? Is it checking each and every attribute and sees if there is a match? Thanks for your help! -
"OSError: dlopen(/home/bob/local/lib/libgeos_c.so, 6): image not found"
I am trying to use django-location-field, and I've been running into several issues when I try to run 'makemigrations'. firstly, here is the model that includes django-location-field: models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.gis.geos import Point from location_field.models.plain import PlainLocationField # Create your models here. class Location(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) city = models.CharField(max_length=255) plain_location = PlainLocationField(based_fields=[city], zoom=7, default=Point(1, 1)) def __str__(self): return self.city It needed me to install GDAL, which I installed with the following command: brew install gdal which worked. Then, It said I need GEOS, which I downloaded with brew install geos but I needed to include the following path in my settings.py: GEOS_LIBRARY_PATH = '/home/bob/local/lib/libgeos_c.so' Now, the third error is the following: OSError: dlopen(/home/bob/local/lib/libgeos_c.so, 6): image not found Don't really understand what this error is telling me, nor how I would solve it. any thoughts anyone? -
Django Json data as string
I have a project where I have to get JSON data from one API endpoint and then pull some data from this JSON data and send it to another API. From first API I am getting this data: response ={ "abc":"AP003", "data":[ { "d":{ "e":"some data", "f":"some data" } } ] } I extract data from this and send it to another view. response = response.json() response = response['data'] return JsonResponse(json.dumps(data),safe=False,content_type='application/json') When I do this I get response but data I get is in string form and not in JSON form. How to get JSON data and send it to template as it is? -
scrapyd-deploy throws 404 error
I am trying to deploy Django+Scrapy project on Ubuntu 16.04. When I run scrapyd-deploy - I get: Packing version 1526639948 Deploying to project "first_scrapy" in http://my_ip/addversion.json Deploy failed (404): <full HTML code of '404.html' page> When I run scrapyd-deploy -l - I see: default http://my_ip My scrapy.cfg: [settings] default = first_scrapy.settings [deploy] url = http://my_ip username = root password = rootpassword project = first_scrapy What am I doing wrong? -
jmeter jwt authentication and the post
I am setting up a test against single EC2 instance. In that EC2 it has only Django application. It has no S3/CloundFront or RDS assist it. Everything purely run on Docker and basic setup of memory and CPU. My goal is I want to see the empirical performance of my single EC2. It will help me do roughly cost estimation on the production. You can skip this and jump to my problem: Here is my production setup 1 load balance 2 nodes with identical setup by using docker image 1 bucket/cloudfront 1 rds Softwares: django==2.0.5 djangorestframework-jwt==1.11.0 djangorestframework==3.8.2 Tools: JMeter 4.0 r1823414 javac 10.0.1 java 10.0.1 2018-04-17 Java(TM) SE Runtime Environment 18.3 (build 10.0.1+10) Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.1+10, mixed mode) Parameters: Thread Group - Number of Threads: 10 - Ramp-up period: 1 - Loop Count: 1 HTTP Header Manager - Content-Type, Application/json - Authorization: jwt ${__token} HTTP Request - http - localhost - port: 8000 - POST - Path: /api-token-auth/ - Body data : {"username": "myname", "password": "mysecretpassword"} At this point test is good. All are green I can have token back from Django. Problem: I add JWT Extractor to extract response's payload and get my token … -
Function not producing the same results even when transactions are rolled back
I am testing a new feature that runs on certain models that need to be in a particular state which is product of a costly operation, so running this every time I want to test the feature is a waste of time, so I figured rolling back the transactions would do. try: with transaction.atomic(): m = MyModel.objects.get(id=some_id) for e in m.element_set.filter(some_filter): new_feature(m, e) log_state(m) raise DatabaseError except DatabaseError: log_state(m) # this looks like the state was restored This block is being used straight in a view method, with no other context variables that may be messing around with the results. The first time everything runs as expected. I would expect the exact same behavior in the following runs, since we are rolling back the changes. However the result is completely different. What could possibly be the reason of this? If we are reverting the database changes to the very same state it had before running the function for the first time, how are we getting a different result? -
Edit a model comment Django
I am stuck because I want to add a comment in my model and I do not know how to do it. Can you help me please ? Here is my form in forms.py: class UpdateActu(forms.ModelForm): class Meta: model = models.Actu fields = ['commentaire'] widgets = { 'commentaire': forms.Textarea(attrs={'class': 'form-control', 'id': 'exampleTextarea'}) } Here is my model : class Actu(models.Model): commentaire = models.TextField(max_length=200, null=True) region = models.CharField(max_length=30, null=True) def __str__(self): return self.region And here is my view : def index_region(request,region): \\I delete the other part to have better visibility form = UpdateActu() context = { 'form': form, } return render(request, '../templates/index.html', context) I know that currently, I just send my form but I do not know how to do the treatment to modify the old comment by the new one. Thank you in advance. -
add image to FileField in Django
I'm using Django building a website and I'm trying to let the user upload an image to be used, here is my files : settings.py # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home2/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' models.py class test1(models.Model): dress_name = models.CharField(max_length=250, default='dress') dress_size = models.CharField(max_length=50, default='5') docfile = models.FileField(upload_to='documents/%Y/%m/%d',default ='upload') views.py def home(request): all_dress = test1.objects.all() context = { 'all_dress': all_dress, } return render(request, 'fostania/home.html', context) and here is how I used it in my template HTML {% for item in all_dress %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ item.docfile.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ item.dress_name }}</h5> <p class="card-text">{{ item.dress_size }}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {% endfor %} finally, the image never shows .. it is always an error in the link !! Please note that image goes there in the static/media file after uploading, So i think it is some kind of URL error! -
nested loop in django template is not showing correct output
I am trying to print brand and it's links and I am using nested loops but it is not showing correct output here is my code {% for brand_report in brand_reports %} <h1> REPORT for Brand: {{ brand_report.brand.name }}</h1> {% for link in brand_report.links.all %} <h3>link:</h3><a href="{{ link.url }}">{{link.url}}</a> {% endfor %} {% endfor %} Desired output is REPORT for Brand: SizCom link: https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET REPORT for Brand: SizCom link: https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET But i am getting output like this REPORT for Brand: SizCom REPORT for Brand: SizCom link: https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET link: https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET Don't know what i am doing wrong -
django humanize timesince do not printing
My django view is passing this inside my template: context={'material':material_id,'inventory_list':inventory,'now_time':datetime.now() Inside my material object I have this field that is update each new save: last_update = models.DateTimeField() And I'm trying to print an humanized time ago in the screen so I'm doing this: {{now_time | timesince:material.last_update }} It's not printing anything, despite separately both variables are appearing correctly: {{now_time}} {{material.last_update}} OUTPUT: May 18, 2018, 11:10 a.m. May 18, 2018, 10:45 a.m. -
How to extend django.contrib.auth views?
How I've Arranged Templates : I have placed my login.html in /templates/registration folder of Django. So, the Django takes necessary care of accounts/login ,accounts/logout url requests and renders as per request. And I haven't to code for the individual login and logout functions. What I am trying to Achieve : I want to authenticate users at login request, when they requests the login page: If user is anonymous user, I want to render the normal login page. However, If the user is authenticated thats already logged in. I want to display an error and not the logged page. I want to achieve this in the views.py and urls.py and not in the templates by: {% if user.is_authenticated %} {% if user.is_anonymous %} Urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views urlpatterns=[ url(r'^register/$', views.register, name='register'), url(r'^logout/$', auth_views.logout, {'next_page' : 'Homepage'}, name='logout'), ] -
Django does not send emails to admins on error 500
I have following settings in my Django project EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'somemail@gmail.com' SERVER_EMAIL = 'somemail@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'somemail@gmail.com' #your acc and pass EMAIL_HOST_PASSWORD = 'somepassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True ADMINS = (('myusername', 'myemail@gmail.com'),) But with this Django still does not send emails on 500 error to admins. What is wrong here? It is said in the docs that I should enter a full name to ADMINS settings. Is that full name from default User model? What if I have empty those fields? P.S. send_mail() from python shell works with those settings. -
Upload video with created automatically thumbnail in Djnago 2
I want to upload .mp4 and .mov videos in my django website with automatic thumbnail generation. Thumbnails should be create in .jpg or .png that will be save in ImageField and also video in FileField. I'm using Python 3.6.1, and Django 2.0. Please advise me how to create a video similar to youtube. Is there any opensource modules/plugins available for this this ? Kindly, Help me. Thank You, Pravin Kumar enter image description here -
Django Models XOR at the model level?
I am implementing approach #2 on this website. Currently, I have: class Owner(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) group = models.OneToOneField(Group, null=True, blank=True, on_delete=models.SET_NULL) My requirement is that a Owner will have only a User or Group but not both. How can I enforce this when my scripts are creating them by directly calling Owner.create? -
Django template multiple tables with only slightly modified data
I want to display two tables on my page where only one column is modified and all the others are the same. I was wondering if there's any other way which is more efficient than simply looping two-times and creating the table two times? What I would do right now is: # Example models class Question(models.Model): question = models.TextField() class Answer(models.Model): question = models.ForeignKey(Question) score = models.Integerfield() SCORETYPES = ( (1, 'initial'), (2, 'current'), ) scoreType = models.Integerfield(choices=SCORETYPES) def __str__(self): return "Answer: " + scoreType In my view I would link the question with the answers as so: # Example view questions = Question.objects.prefetch_related(Prefetch('answer_set', to_attr='answers')).all() Which means that my question object would look like this for each question question.answers = [<Answer: Initial>, <Answer: Current>] and then in my template I would print them like this # Example template {% for question in questions %} {% for answer in question.answers %} <p>{{ answer.scoreType }}: {{ answer.score }}</p> {% endfor %} {% endfor %} This would work but now I want to create a table for all the initial scores and one table for all the current scores so you get something like this: Initial Scores Question Score Q1 2 Q2 3 …