Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Determine how many times a Django model instance has been updated
I'm trying to find a generic way to get a count of how many times an instance of a model has had any of its fields updated. In other words, in Django, how do I get a count of how many times a specific row in a table has been updated? I'm aiming to show a count of how many updates have been made. Let's say I have: class MyModel(models.Model): field = models.CharField() another_field = models.IntegerField() ... and I have an instance of the model: my_model = MyModel.objects.get(id=1) Is there a way to find out how many times my_model has had any of its fields updated? Or would I need to create a field like update_count and increment it each time a field is updated? Hopefully there is some kind of mechanism available in Django so I don't have to go that route. Hopefully this isn't too basic of a question, I'm still learning Django and have been struggling with how to figure this out on my own. -
Django 1.11 PostgreSQL - "SET TIME ZONE" command on every session
We are working out a couple of performance issues on one of our web sites, and we have noticed that the command "SET TIME ZONE 'America/Chicago'" is being executed so often, that in a 24 hour period, just under 1 hour (or around 4% of total DB CPU resources) is spent running that command. Note that the "USE_TZ" setting is False, so based on my understanding, everything should be stored as UTC in the database, and only converted in the UI to the local time zone when necessary. Do you have any ideas on how we can remove this strain on the database server? -
How to Parse Image URL and Save It On Cloudinary With Django?
I'm having some issues integrating Cloudinary into Django. I have a form on my site, that excepts URLs. This URL is then being parsed with BS4 to find an image URL: def add(request): ... product.image_url = soup.find('meta', property='image')["content"] ... I then pass URL to cloudinary.uploader: ... product.image = cloudinary.uploader.upload(product.image_url) product.save() return redirect(product.get_absolute_url()) I've added the CloudinaryField to the product's class: class Product(models.Model): image = CloudinaryField('image') When I'm trying to add the product, I'm getting the following error: ProgrammingError at /product/add can't adapt type 'dict' Would appreciate your help with this one. -
Projecting 2 google charts of html page using django
I am trying to render two charts on html page using django whereas the data is being imported from the model. I've tried putting charts in a list and then send it but it gives an error "'list' object has no attribute 'get_header'" chart = [] chart.append(PieChart(data_source, html_id='piechart_id', options={'pieHole' : 0.4})) chart.append(AreaChart(area_graph)) context = {'Portfolio': chart} return render(request,'displaypage/graphs.html', context) -
AttributeError: module 'django.db.models' has no attribute 'Models'
When im trying to migrate a new app onto the server i get this error - AttributeError: module 'django.db.models' has no attribute 'Models'- in terminal. Also i dunno if this helps but im using PyCharm. I am very fresh to django and web development so any tips will help. thanks from django.db import models # Create your models here. class product(models.Model): item = models.Textfiels() description = models.Textfields() price = models.Textfields() -
How to make python manage.py -args into short_command_name -args?
I'd like to write a simple bash script to write in windows cmd p args instead of python manage.py args but i have no experience in bash. Can you help me? -
Connect Django Amazon Ligthsail Mysql
i have a app that try to connect to amazon ligthsail Mysql but get this error: (1045, u"Access denied for user 'toor'@'localhost' (using password: YES)") my settings: DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'SERVER':'host_amazon', 'PORT': '3306', 'USER': 'toor', 'PASSWORD': 'q1w2e3r4t5' , } } i create a user from mysql workbench with this: create user toor identified by 'q1w2e3r4t5'; grant all on my_db.* to 'toor'@'%'; flush privileges; and try this code: grant all on my_db.* to toor@localhost identified by 'q1w2e3r4t5' with grant option; but get the same error please some one suggest. thanks..!! -
Combining Mapbox, Django and Javascript to generate map markers
I have a django model called PicData. It contains the name of a jpeg file, the date the photo was taken and latitude and longitude where it was taken. I have the jpeg file stored in a static/image file. It will be added to periodically. I'm using Mapbox to create a map with a marker that using the coordinates from the model, and the jpg file as background image. I'm not sure how to combine Django with Mapbox. I'm using Django 2.2. I have the map working when the coordinates and background image are hard coded. When I try to create a loop through the model records I get error message: Unclosed tag on line 62: 'for'. Looking for one of: empty, endfor. I've done research on Mapbox, Javascript and Django, but nothing answers my exact question. I am new to Django, so I apologize in advance if it is too simple. models.py from django.db import models class PicData(models.Model): FileName = models.CharField(max_length=200) DateTaken = models.DateField() Lat = models.FloatField() Long = models.FloatField() Relevant part of index.html {% for pic in PicData %} var geojson = { type: 'FeatureCollection', features: [{ type: 'Feature', geometry: { type: 'Point', coordinates: [{{pic.long}}, {{pic.lat}}] }, properties: … -
Export .wav from Audio Segment to AWS S3 Bucket
I'm using IBM's Text-to-Speech API to run speaker detection. I used pydub to concatenate several .wav files into one, but I cannot pass an AudioSegment to IBM. My questions are: Can I export my file directly to an AWS S3 bucket, as I can later retrieve from there? How else could I pass the AudioSegment? Can I encode it differently as a variable, so exporting it without saving it in memory, if that makes sense? This is the formats IBM can read application/octet-stream audio/alaw (Required. Specify the sampling rate (rate) of the audio.) audio/basic (Required. Use only with narrowband models.) audio/flac audio/g729 (Use only with narrowband models.) audio/l16 (Required. Specify the sampling rate (rate) and optionally the number of channels (channels) and endianness (endianness) of the audio.) audio/mp3 audio/mpeg audio/mulaw audio/ogg audio/ogg;codecs=opus audio/ogg;codecs=vorbis audio/wav audio/webm audio/webm;codecs=opus audio/webm;codecs=vorbis I love pydub and it's been an amazing tool to work with so far. Thank you for making it! -
Replace Amazon s3 with S3ForMe
I have added to my Django application the storage of static and multimedia files in bucket amazon s3. I need to change to another option because of problems with my account. I want to take advantage of S3ForMe. In order to configure everything efficiently, I changed the keys, and I have to change API endpoint (which looks like this): <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>15554191115cb5cfe7adb60</RequestId> <HostId>storage0-3.s3for.me</HostId> </Error> I have no idea where to make this change in my django application or on PythonAnywhere. Where to change these APIs. When adding amazon s3, I never added something like that. Any help will be appreciated. -
How to manually add objects to a Django model using a for loop?
relatively new to Python and very new to Django so looking for some help with this. I'm trying to create a user rank-up system similar to what you'd find in an role-playing game (i.e. the user gains levels by getting experience points) So far I have an app in my project with this simple model within its models.py. I've already ran migrations and this currently empty table is sat in my database: class UserLevel(models.Model): level_rank = models.IntegerField() xp_threshold = models.IntegerField() Now what I want to do is add levels 1 to 100 (integers) to level_rank. So there would be 100 instances. Level 100 would be the max level. In addition, the xp_threshold would increment by 50% each level. So for example, level 1 would have an xp_threshold of 100, level 2 would have 150, level 3 would have 225 and so on. I don't particular care how the numbers are rounded. I'm using Django v2.0.13 So far, I have this: class UserLevel(models.Model): level_rank = models.IntegerField() xp_threshold = models.IntegerField() levels_range = range(1,101) for level in levels_range: UserLevel.objects.create(level_rank=level) But this is giving me a NameError saying that UserLevel is not defined. I know I could manually just pump this data into Django's … -
Using a SQL database and a NoSQL database
How do I connect Postgres and MongoDB at the same time in my Django project? I'm just clueless, and the MongoEngine documentation wasn't exactly helpful. Like what would I do in the settings, models, and views.py? Absolutely clueless. I mean, would I use a db_alias? -
Django - select specific columns using Model field properties with only
Is there a way to refer to the fields not using strings? I've been looking around at documentation and I only see examples of only() with strings rather than referred to the field properties of the Model object. I try to avoid using 'magic strings' when I can. Is this possible? For example, looking at the only documentation and other stack posts here all have the only() method with strings as arguments. -
How do I test my AJAX function defined in my views file?
I'm using Django and Python 3.7 and tryihng to tests an AJAX request from a view, located at web/views/tax_calculator.py # Basic function that serves the default page def get(request): return render(request, "web/template/tax_calculator.html", {}) # This is an Ajax call that will calculate the overall taxes you pay for # an S-Corp vs a sole proprietorship def post(request): state = request.GET.get('state', None) gross_income = request.GET.get('gross', None) owner_salary = request.GET.get('salary', None) data = { 'sole_pr_taxes': TaxCalculatorService.calc_sole_pr_taxes(state, gross_income), 's_corp_taxes': TaxCalculatorService.calc_s_corp_taxes(state, gross_income, owner_salary), } return JsonResponse(data) Here is my test file, located at web/tests/test_views.py from django.test.client import Client import json from web.models import * c = Client() class ViewTests(TestCase): # Basic test to verify we can get valid return data def test_calculate_tax(self): state = 'MN' gross = 100000 salary = 75000 json_data = json.dumps({'state': state, 'gross': gross, 'salary': salary}) response = c.post('/content/vote/', json_data, content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 302) # this is OK. print(response.content) self.assertEqual(response.content, 2) This results in the error below. What else do I need to do to make my test understand my Ajax request? ====================================================================== ERROR: test_calculate_tax (web.tests.test_views.ViewTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/davea/Documents/workspace/myproject/web/tests/test_views.py", line 20, in test_calculate_tax response = c.post('/content/vote/', json_data, AttributeError: 'Client' object has no attribute 'post' ---------------------------------------------------------------------- Ran … -
Custom SQL code for custom field type in Django migration
My project contains a large number of tables which have timestamp fields created_at, and updated_at, which signify, respectively, when the row was created, and most recently modified. Each time I create a new model with these fields, I add the following RunSQL statement to the migration: migrations.RunSQL('CREATE TRIGGER some_trigger_name BEFORE UPDATE ON my_table FOR EACH ROW EXECUTE PROCEDURE update_modified_column()'); A large number of database operations happen outside of Django, so it's necessary to track this in the database layer, as opposed to just using updated_at = models.DateTimeField(auto_now=True) when defining the model. Is it possible to create a custom field type, which when I run the makemigrations command, will automatically generate that RunSQL statement? -
How to create a select button that takes me to the content of the chosen item?
I have 6 areas and each area has 5-6 countries. I need to make a dropdown list of 6 areas and when I click the area name all the countries that belong to the area should appear underneath. I created 6 models with the area names. I created a model with country names. But I don't know how to connect them. -
django edit forms dont keep values
I have a create a simple Django forms for add and and edit forms. my problem is in people field where I use ModelChoiceField. in edit forms all values parse correct except that field ModelChoiceField. In edit forms that field is empty and don't keep values ,any idea why ?? def edit_work(request, pk): instance = get_object_or_404(work, id=pk) form = workForm(request.POST or None,instance=instance) if form.is_valid(): note = form.save(commit=False) note.save() return HttpResponseRedirect('/work/success/') return render(request,'edit_work.html', {'form': form}) def add_work(request): if request.method == "POST": form = workForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.save() return render(request, "succes/erga_success.html") else: form = workForm() return render(request, 'add_work.html',{'form':form}) forms.py class workForm(forms.ModelForm): peaople=forms.ModelChoiceField(queryset=User.objects.all(),required=False, error_messages={ 'invalid': _("---")}) class Meta: model = work fields = (__all__") html page : <form enctype="multipart/form-data" method="POST" action="">{% csrf_token %} {{form.peaople}} ......... <input type="submit" value="create"> </form> -
Build react form based on serializer of Django Rest Framework
I want to build web app where users can add different ads for sale(cars,apartments, gadgets etc...) and each of this categories models in django are specific and need specific fields in form for creating ad. Creating this forms using django is easy by using ModelForms. DRF documentation says that A serializer class is very similar to a Django Form class, and includes similar validation flags on the various fields..... . So I guess I will create form on base of serializers. My question is: How make a single React component which will render form on base of different serializers that frontend gets from Django-Rest-Framework? Please any advice or links where I can read about this . If you need I can share some code . Thank you in advance. -
Serializer complains about request data
I need to append some data to the request, so I did the following: data = {'my_data': 1, **request.data} ... serializer = MySerializer(data=data) serializer.is_valid() But the serializer is complaining about the fields not being in the correct format: "Not a valid string." It says the same on all of them. Makes sense because I see it's creating a dict filled with lists: {'attr1':[1], 'attr2':[2], ..., 'my_data':1} What doesn't make sense is that this works just fine: serializer = MySerializer(data=request.data) serializer.is_valid() Even though the QueryDict object has all fields wrapped in a list too I also tried the following: data = {'my_data': [1], **request.data} But now it also complains about the new field. What am I doing wrong? -
Best method to Redirect appid.appspot.com to custom domain for Django App hosted on app engine
I apologize in advance for asking this question since it has been asked many times but i could not find a Django specific solution which can fix this issue. Description: Django: 2.1 Python: 3.7 App Host: Google app engine Domain Provider: Google domains I have a Django App hosted on google app engine with [id].appspot.com url. I have also registered a custom domain e.g. www.example.com on google domains. I want to redirect anyone trying to access [id].appspot.com to www.example.com parmanently (301). My custom domain is working fine. So far based on google and stackoverflow searches I have found the following: Add following canonical tag to each page <link rel="canonical" href="https://www.example.com/" /> This should notify search engines which domain you prefer when same content is available from multiple domains. I have added this to my site header, but this seems like a workaround. Use check and redirect function: This post has some good approaches for webapp2 apps. However it is 10 years old post so not sure if any of these solution directly work or may need code changes. In the answer "Alex Martelli" suggested to check os.environ['HTTP_HOST'].endswith('.appspot.com') and redirect. I am not sure how to accomplish it in Django app … -
Django request Session not linking with logged in user model
Despite calling authenticate and login for a valid username and password combination, when moving to another view the session fails to link with the user's user model. The model is instead an "AnonymousUser" and they cannot progress because it is required that they are a valid login user. I've had a system that has worked well for quite some time (as I imagine everyone says before they have a problem...) To avoid having to add "requre_loging" decorator to every view, I have made a middleware that checks that the user is login and shall redirect them if they are not, to the login page. This setup has been working for some time, but, recent changes to the user model has shown that users that were present pre-migration are no longer able to log in. What is baffling about this is that if they have their passwords updated via the django admin they can then access the site as normal authentication view import django.http from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout, update_session_auth_hash, models as admin_models from django.conf import settings from .models import LoginAttempts import logging logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) # Define the alert to be given to … -
Best option to compress Images before uploading to s3
I want to compress images before uploading to aws s3 bucket for cost reduction. I am using S3Boto3Storage and have noticed that files get pushed to bucket before django model gets saved. So, to resize the image during the save will increase the inboud/outbound traffic. The other solution would be using aws lambda. But I dont know what is the best solution in terms of cost optimization -
my form field doesn't appear at html file
I'm trying to fix this problem... I made a simple post form with forms.py but it doesn't show up at the HTML file. I searched at google but I still don't know how to fix it views.py from django.shortcuts import render from contact.forms import contactForm def contact(request): form = contactForm(request.POST) if form.is_valid(): return request.POST context = locals() template = 'contact.html' return render(request, 'contact/contact.html') contact.html {% block content %} <h1> Contact doesn't appears.. </h1> <form method = "POST">{% csrf_token %} {{ form.as_p }} <input type = "submit" value = "submit form" class = 'btn btn-default' /> </form> {% endblock %} forms.py from django import forms from django.shortcuts import render class contactForm(forms.Form): name = forms.CharField(required = False, max_length = 100, help_text='100 characters max.') email = forms.EmailField(required = True) comment = forms.CharField(required = True, widget = forms.Textarea) -
How to make an online community website like stack overflow using Django and MySQL?
I have been given a project on my Internet Programming sessional to make an online community website like Stack Overflow using Django and MySQL. But I dont know how to start or where to start. Can you give me any recommendations or suggestions please? -
how to do assignments for variable in django template tag
i want to do assessment in django template tag for this code: {% for ins in ob %} {% if ins.heur = 'here' %} a==1 some stuff .. {% endif %} {% endfor %} {% if a!=1 %} stuff {% endif %}